洞察探索小游戏大厅如何提升用户体验与企业转型效率
1077
2022-11-08
Node.js:MySQL.js的基本操作增删改查
文档:
table table_user( id int primary key auto_increment, name varchar(20) not null, age int not null default 0);
安装依赖
node -vv16.14.0pnpm
package.json
{ "type": "module", "dependencies": { "dotenv": "^16.0.1", "mysql2": "^2.3.3" }}
配置文件 .env
DATABASE_URL='mysql://root:123456@127.0.0.1/data'
代码实现
import "dotenv/config";import mysql from "mysql2";function getConnection(config) { const connection = mysql.createConnection(config); // 自定义占位符 // connection.config.queryFormat = function (query,) { if (!values) return query; return query.replace( /\:(\w+)/g, function (txt,) { if (values.hasOwnProperty(key)) { return this.escape(values[key]); } return txt; }.bind(this) ); }; // 异步查询 connection.querySync = function (sql,) { return new Promise((resovle,) => { connection.query(sql, params, function (err, result,) { if (err) { reject(err); } else { resovle(result); } }); }); }; return connection;}
查询示例
// 数据插入async function insertRow(connection) { let sql = "INSERT into table_user (name, age) VALUES (:name, :age)"; let params = { name: "Tom", age: 23 }; let result = await connection.querySync(sql, params); console.log(result); // ResultSetHeader { // fieldCount: 0, // affectedRows: 1, // insertId: 1, // info: '', // serverStatus: 2, // warningStatus: 0 // }}// 数据修改async function updateRow(connection) { let sql = "UPDATE table_user SET name = :name, age = :age WHERE id = :id"; let params = { name: "Jack", age: 24, id: 1 }; let result = await connection.querySync(sql, params); console.log(result); // ResultSetHeader { // fieldCount: 0, // affectedRows: 1, // insertId: 0, // info: 'Rows matched: 1 Changed: 1 Warnings: 0', // serverStatus: 2, // warningStatus: 0, // changedRows: 1 // }}// 数据查询async function selectRow(connection) { let sql = "SELECT * FROM table_user WHERE id = :id"; let params = { id: 1 }; let result = await connection.querySync(sql, params); console.log(result); // [ { id: 1, name: 'Jack', age: 24 } ]}// 数据删除async function deleteRow(connection) { let sql = "delete from table_user WHERE id = :id"; let params = { id: 1 }; let result = await connection.querySync(sql, params); console.log(result); // ResultSetHeader { // fieldCount: 0, // affectedRows: 1, // insertId: 0, // info: '', // serverStatus: 2, // warningStatus: 0 // }}(async () => { const connection = getConnection(process.env.DATABASE_URL); // await insertRow(connection); // await updateRow(connection); // await selectRow(connection); await deleteRow(connection); connection.end();})();
参考Node.js 连接 MySQL-菜鸟教程
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~