// 引入 mysql 模块
const mysql = require('mysql');
// 创建数据库连接配置
const connection = mysql.createConnection({
host: 'localhost', // 数据库主机地址
user: 'root', // 数据库用户名
password: 'password', // 数据库密码
database: 'testdb' // 要连接的数据库名称
});
// 连接数据库
connection.connect((err) => {
if (err) {
console.error('Error connecting to the database:', err);
return;
}
console.log('Connected to the MySQL database.');
});
// 执行 SQL 查询
connection.query('SELECT 1 + 1 AS solution', (error, results, fields) => {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
// 关闭数据库连接
connection.end((err) => {
if (err) {
console.error('Error closing the database connection:', err);
return;
}
console.log('Database connection closed.');
});
require 方法引入了 mysql 模块,这是 Node.js 中用于连接和操作 MySQL 数据库的模块。mysql.createConnection 方法创建了一个数据库连接实例,并传入了连接所需的配置信息,如主机地址、用户名、密码和数据库名称。connection.connect 方法来建立与 MySQL 数据库的连接。如果连接失败,会输出错误信息;否则,会输出成功连接的消息。connection.query 方法执行一个简单的 SQL 查询(例如 SELECT 1 + 1 AS solution),并将结果输出到控制台。connection.end 方法关闭数据库连接,并输出关闭成功的消息。上一篇:mysql in走索引么
下一篇:mysql 字段长度函数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站