求知 文章 文库 Lib 视频 iPerson 课程 认证 咨询 工具 讲座 Model Center   Code  
会员   
要资料
 
 

mysql教程
MySQL快速学习入门
MySQL是什么
MySQL安装
MySQL示例数据库
MySQL导入示例数据库
MySQL基础教程
MySQL查询数据
MySQL WHERE语句
MySQL插入数据
MySQL更新表数据
MySQL删除表数据
MySQL创建与删除数据库
MySQL创建表
MySQL修改表结构
MySQL重命名表
MySQL数据类型
高级部分
MySQL技巧
MySQL存储过程
MySQL视图
MySQL触发器
MySQL管理
MySQL全文搜索
MySQL函数
应用程序连接
MySQL+Node.js连接和操作
Python+MySQL连接和操作
 
 

Node.js连接MySQL创建表
885 次浏览
9次  

在本教程中,您将学习如何从node.js应用程序连接到MySQL数据库,并创建一个新表。

要从node.js应用程序连接到MySQL并创建表,请使用以下步骤:

连接到MySQL数据库服务器,请参考:
http://lib.uml.com.cn/ebook/mysql/mysql24-1.asp

调用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数据库中创建一个新表。


您可以捐助,支持我们的公益事业。

1元 10元 50元





认证码: 验证码,看不清楚?请点击刷新验证码 必填



885 次浏览
9次
 捐助