掌财社教你从 Node.js 连接到 MySQL 数据库服务器

首先,使用以下语句导入mysql模块:

let mysql = require('mysql');

Js

其次,通过调用createConnection()方法并提供MySQL服务器上的详细信息(如主机,用户,密码和数据库),建立与MySQL数据库的连接,如下所示:

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

Js

在本示例中,我们在本地数据库服务品上与todoapp数据库的连接。

第三步,在连接对象上调用connect()方法连接到MySQL数据库服务器:

connect()方法接受一个具有err参数的回调函数,如果发生任何错误,它将提供详细的错误。

connection.connect(function(err) {
  if (err) {
    return console.error('error: ' + err.message);
  }

  console.log('Connected to the MySQL server.');
});

Js

完整的connect.js程序代码如下所示 -

let mysql = require('mysql');

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

connection.connect(function(err) {
  if (err) {
    return console.error('error: ' + err.message);
  }

  console.log('Connected to the MySQL server.');
});

Js

我们来运行并测试一下connect.js程序 -

F:\worksp\mysql\nodejs\nodejs-connect>node connect.js
openssl config failed: error:02001003:system library:fopen:No such process
Connected to the MySQL server.

Shell

如果看到如上所示的“connected to the MySQL server”的消息,那么恭喜,您已经从node.js应用程序成功连接到MySQL数据库服务器。

假设使用MySQL用户账号的密码有错,并尝试连接到数据,您将收到一条错误消息:

F:\worksp\mysql\nodejs\nodejs-connect>node connect.js
openssl config failed: error:02001003:system library:fopen:No such process
error: ER_ACCESS_DENIED_ERROR: Access denied for user 'root'@'localhost' (using password: YES)

SQL

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_45378258

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值