今天再记一篇昨天在 nodeJs 中实现对 mysql 的数据库服务器的链接,及简单的 SQL 查询操作,方便日后遇到此类开发时作为一种回顾。
当前的实践环境:
- 操作系统:windows 10
- 编程语言:typeScript (是 javaScript 超集版)
安装依赖库
要想实现 nodeJs 访问 mysql 数据库,首先要安装两个依赖库分别是第三方的 knex 和官方的 mysql
npm install knex --save npm install mysql --save
建立与数据库服务器的连接
首先是配置好数据库服务器的信息
export const dbConfig: any = { host: '127.0.0.1', database: 'p4pproduct', user: 'root', password: '123456' };
然后再写入建立起连接的代码
import {dbConfig} from "./config"; import * as Promise from 'bluebird';
export class DBServer { private _client: any; constructor() { this._client = require('knex')({ client: 'mysql', pool: { min: 2, max: 10 }, connection: dbConfig }); } …… }
简单查询
selectProductIds(tableName: string, ids: number[]) { return new Promise(resolve => { var fields = ['Id']; this._client(tableName).select(fields).whereIn('ProductId', ids).then(data => { resolve(data); }).finally(() => { return this._client.destroy(); }); }); }
执行 SQL 查询
有的时候会遇到想知道当前拼接后的 SQL ,在执行时他的完整语句长啥样。
this._client(tableName).select(fields).whereIn('ProductId', ids).toSQL().toNative()
insert 数据
/** * @param {数据表名} tableName * @param {要插入的数据,格式可以为 JSON} parmas */ insert(tableName: string, parmas: any[]) { // console.log(parmas); this._client(tableName).insert(parmas).then((idx) => { return; }).finally(() => { return this._client.destroy(); }); }
update 数据
/** * @param {数据表名} tableName * @param {更新的数据,格式可以为 JSON} parmas * @param {更新的条件,格式可以为 JSON} options */ update(tableName: string, parmas: any, options: any) { this._client(tableName).where(options).update(parmas).finally(() => { return this._client.destroy(); }); }
delete 数据
/** * @param {数据表名} tableName * @param {删除的条件,格式可以为 JSON} parmas */ delete(tableName: string, parmas: any) { this._client(tableName).where(parmas).del().then(idx => { return; }).finally(() => { return this._client.destroy() }); }
执行手写SQL
在 knex 中有许多拼接式的写法,方便组装 sql ,如上面的几个,但在复杂的编辑中也会遇到要手写 SQL 的情况。
query(sql: string) { return new Promise(resolve => { this._client.raw(sql).then(data=>{ resolve(true); }).finally(() => { return this._client.destroy(); }); }); }
更多的细节看官方文档
转载请注明:隨習筆記 » NodeJs笔记:访问 mysql