반응형

일렉트론 MySQL 연동

일렉트론에서 MySQL을 연동하여 데이터를 읽어오는 것을 배워봅니다.

 

이 글의 동영상 강의입니다.

https://youtu.be/3EqAud7cBGY

Database와 Data 생성

MySQL Workbench를 실행합니다.

아래 쿼리로 스키마를 생성합니다.

 

CREATE SCHEMA test;

사용자를 생성하고 권한을 설정합니다.

CREATE USER 'test'@'localhost' identified with mysql_native_password by 'test';
GRANT ALL PRIVILEGES ON test.* TO 'test'@'localhost';
flush privileges;

Workbench에서 Connection을 추가합니다.

New Connection

설정한 Connection으로 접속합니다.

Connection

테이블을 생성합니다.

CREATE TABLE IF NOT EXISTS `test`.`user` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `userid` VARCHAR(50) NULL,
  `username` VARCHAR(50) NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

아래와 같이 생성된 테이블에 데이터를 입력합니다.

insert into test.user(userid, username) values ('codegear', '코드기어');
insert into test.user(userid, username) values ('ironman', '아이언맨');
insert into test.user(userid, username) values ('spiderman', '스파이더맨');

data 확인

일렉트론 Appllication 만들기

다음 스크립트로 일렉트론 Application을 만듭니다.

npx create-electron-app electron-mysql

mysql 사용을 위해 'mysql' 패키지를 설치합니다.

npm i mysql

src/index.html을 다음 코드를 입력합니다.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="script-src 'self';">
    <title>Hello World!</title>
    <link rel="stylesheet" href="index.css">
  </head>
  <body>
    <h1>💖 Hello World!</h1>
    <p>Welcome to your Electron application.</p>
    <input type="button" id="btn" value="connectToMysql"/>
    <div id='users'></div>
    <script src='./function.js'></script>
  </body>
</html>

src/function.js를 만들고 다음 코드를 입력합니다.

const mysql = require('mysql');

function setInnerHTML(text) {
    const element = document.getElementById('users');
    element.innerHTML += '<div>'+text+'</div>';
  } 

document.getElementById("btn").addEventListener("click", ()=>{
    //ipc.send('getUsers');
    var connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'test',
        password : 'test',
        database : 'test'
    });

    connection.connect();

    connection.query('SELECT * from USER', function (error, results, fields) {
        if (error) throw error;
        console.log('users: ', results);
        results.forEach(user => {
            setInnerHTML(user.username);
        });
    });

    connection.end();
})

application을 실행합니다.

npm start

"require is not defined" 오류를 확인할 수 있습니다.

require is not defined

src/index.js의 createWindow에 다음 내용을 추가합니다.

    webPreferences: {
      nodeIntegration: true,
      contextIsolation : false
    }

const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation : false
    }
  });

Application을 다시 실행하면 아래와 같은 결과를 확인할 수 있습니다.

Completed!!!

반응형

+ Recent posts