electron连接MySQL数据库的代码
时间: 2023-06-15 19:07:47 浏览: 68
以下是使用 Node.js 和 electron 连接 MySQL 数据库的代码示例:
首先需要安装 mysql 和 electron 两个包:
```
npm install mysql electron --save
```
然后在主进程(main.js)中编写以下代码:
```js
const { app, BrowserWindow } = require('electron');
const mysql = require('mysql');
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
});
mainWindow.loadFile('index.html');
mainWindow.on('closed', function () {
mainWindow = null;
});
const connection = mysql.createConnection({
host: 'localhost',
user: 'username',
password: 'password',
database: 'database_name'
});
connection.connect((err) => {
if (err) {
console.error('Failed to connect to MySQL database', err);
return;
}
console.log('Connected to MySQL database');
});
}
app.on('ready', createWindow);
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', function () {
if (mainWindow === null) {
createWindow();
}
});
```
在上述代码中,我们首先创建了一个窗口,然后使用 `mysql.createConnection()` 方法创建了一个 MySQL 数据库连接。在 `connect()` 方法中,我们尝试连接到 MySQL 数据库并打印结果。
请注意,这段代码仅在主进程中使用。如果你希望在渲染进程中连接到 MySQL 数据库,你需要使用 IPC(进程间通信)机制将连接传递给主进程。
希望对你有所帮助!