企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] >[success] mysql 插件 github 连接:[https://www.npmjs.com/package/mysql](https://www.npmjs.com/package/mysql) ## 1. 安装插件 > 插件安装的依赖工具以 `yarn` 为例 ~~~ yarn add mysql ~~~ ## 2. connnections >[success] 详情可见:[establishing-connections](https://www.npmjs.com/package/mysql#establishing-connections) ### 2.1 mysql.createConnection(options) > 具体案例可查看本文档内 **案例 - 数据库连接** mysql.createConnection 是创建数据库连接的方法, 返回 connection 实例对象 ~~~ const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'pmz.2580', database: 'test' }); ~~~ ### 2.2 connection-options >[success] 详情可见:[connection-options](https://www.npmjs.com/package/mysql#connection-options) connection-options 是连接数据库的必填项, 案例中只设置了一部分的 options,更多可查看上面的详情 ~~~ // 本例中 options { host: 'localhost', user: 'root', password: 'pmz.2580', database: 'test' } ~~~ ### 2.2 connection 由 mysql.createConnection 创建的对象,通过调用对象的方法实现连接、操作数据库、断开数据库连接 ### 2.2.1 connection.connect 建立数据库连接 ~~~ connection.connect(function(err) { if (err) { console.error('连接错误: ' + err.stack); return; } console.log('数据库连接的线程标识 ' + connection.threadId); }); ~~~ ### 2.2.2 connection.query 通过 sql 语句实现数据库操作 ~~~ const sql = 'SELECT * FROM movies_detail'; connection.query(sql, function (error, results, fields) { if (error) throw error; console.log('The solution is: ', results); }); ~~~ ### 2.2.3 connection.end 断开连接,确保所有的查询执行之后再使用 ~~~ connection.end(); ~~~ ## 3. 简单的数据库操作语句 简单的表数据操作:“增、删、改、查” ### 3.1 添加表数据 ~~~ insert 表名 (字段名,字段名,字段名...不写默认全部字段) values (数据,数据,数据), (数据,数据,数据), ... (数据,数据,数据); ~~~ ### 3.2 删除表数据 ~~~ delete from 表名 where 过滤条件; ~~~ ### 3.3 更改表数据 ~~~ update 表名 set 字段名=值,字段名=值,... where 过滤条件; ~~~ ### 3.4 查询表数据 ~~~ // 查询表内所有数据 select * from 表名; // 查询表内某字段所有数据 select 字段名 from 表名; // 过滤查询表 select * from 表名 where 过滤条件; ~~~