框架
-
安装mysql2库,在程序中导入使用。
-
使用连接池,设置连接参数。
-
调用execute方法,可以增删改查。
示例
import mysql from "mysql2/promise";
async function main() {
// 在这里修改你的数据库具体信息
const pool = mysql.createPool({
host: 'xxx', // 数据库地址
port: xxxx,
user: 'root', // 数据库账号
password: 'xxx',// 数据库密码
database: 'cqht_xxx', // 数据库名称
waitForConnections: true,//新请求等待空闲连接
connectionLimit: 10 // 最大连接数
});
try {
// 执行数据库查询
const [rows2] = await pool.execute('SELECT * FROM t1');
console.log('查询成功:', rows2);
} catch (err) {
// 捕获错误
console.error('数据库操作失败:', err.message);
} finally {
// 无论如何都关闭连接池
await pool.end();
console.log('连接池已关闭');
}
}
let t=main();
console.log("让程序去读数据库,我来先做点别的事情。");
await t;
console.log("数据库读取完毕,程序结束。");
关注点:
-
以上代码只有查询,普通增删改,修改语句即可。
-
代码
[rows2]=表示只接收返回数组的第一个值。作为查询,会有[数据,元数据]两个值返回,第二个一般不使用。增删改的返回值另有说法,可通过ai了解。 -
使用execute执行sql语句,可以使用占位符,来避免注入。详询ai。
-
代码中的try...catch...finally结构、异步知识点不再赘述,应当关注。
浙公网安备 33010602011771号