npm依赖包mysql使用指南

2023年 7月 19日 26.3k 0

npm依赖包mysql使用指南

npm社区的mysql可以做什么?

npm社区的mysql依赖包,是mysql的node.js驱动程序。它是用JavaScript编写的,不需要编译,并且是100% MIT许可的。

实际使用效果如下:

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'me',
  password : 'secret',
  database : 'my_db'
});
 
connection.connect();
 
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
  if (error) throw error;
  console.log('The solution is: ', results[0].solution);
});
 
connection.end();

数据库连接

在mysql中内置了数据库连接的方法,以及丰富的连接配置项,下面我们分别进行介绍。

建立连接的两种方式

在mysql依赖中有两种数据库连接的建立方式,一种为显式建立,一种为隐式建立

显式建立方式:


var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'example.org',
  user     : 'bob',
  password : 'secret'
});
 
connection.connect(function(err) {
  if (err) {
    console.error('error connecting: ' + err.stack);
    return;
  }
 
  console.log('connected as id ' + connection.threadId);
});

隐式建立的方式:


var mysql      = require('mysql');
var connection = mysql.createConnection(...);
 
connection.query('SELECT 1', function (error, results, fields) {
  if (error) throw error;
  // connected!
});

项目中,个人推荐使用显式建立,隐式建立在使用中,频繁出现无法连接的报错问题。

断开连接

mysql依赖中使用end方法可以优雅的断开链接

connection.end();

数据库连接的配置项内容

let options = {
    host: 'example.org', // 数据库地址
    port:3306, // 数据库端口
    user: 'bob', // 数据库用户
    password: 'secret', // 数据库用户密码
    localAddress:"",//数据库源地址
    socketPath:"",//unix套接字路径
    database:"",//连接的数据库名
    charset:"",//数据库字符集
    timezone:"",//时区设置
    connectTimeout:"",//连接超时时间
    stringifyObjects:false,//是否字符串化对象,默认false
    insecureAuth:false,//是否允许旧身份验证
    typeCast:true,//确定列值是否应该转换为原生JavaScript类型。(默认值:true) 
    queryFormat:"",//自定义查询格式函数。请参阅自定义格式。
    supportBigNumbers:false,//当处理数据库中的大数(BIGINT和DECIMAL列)时,应该启用此选项(默认值:false)。
    bigNumberStrings:false,//启用supportBigNumbers和bigNumberStrings强制大数字(BIGINT和DECIMAL列)总是作为JavaScript字符串对象返回(默认值:false)。启用supportBigNumbers但不启用bigNumberStrings将返回大数字作为String 0
    dateStrings:false,//强制日期类型(TIMESTAMP, DATETIME, date)作为字符串返回,而不是膨胀到JavaScript date对象。可以是true/false,也可以是类型名称的数组,以字符串形式保存。(默认值:false) 
    debug:false,//打印协议细节到标准输出。可以是true/false,也可以是应该打印的数据包类型名称数组。(默认值:false) 
    trace:true,//在Error上生成堆栈跟踪,以包括调用库入口的站点(“长堆栈跟踪”)。对大多数调用有轻微的性能损失。(默认值:true) 
    localInfile:true,//允许LOAD DATA INFILE使用LOCAL修饰符。(默认值:true)
    multipleStatements:false,//允许每个查询使用多个mysql语句。对此要小心,这可能会增加SQL注入攻击的范围。(默认值:false) 
    flags:"",//除默认连接标志外要使用的连接标志列表。也可以将默认的列入黑名单。有关更多信息,请检查连接标志。
    ssl:{}//带有Ssl参数的对象或包含Ssl配置文件名称的字符串。请参见SSL选项。
}

执行查询

mysql中执行查询的方法如下:

connection.query('SELECT * FROM `books` WHERE `author` = "David"', function (error, results, fields) {
  // error will be an Error if one occurred during the query
  // results will contain the results of the query
  // fields will contain information about the returned results fields (if any)
});

query方法的第一个参数除了使用字符串参数执行以外,使用占位符?与??有多种解构方式,具体如下。

第一种,数组参数结构


connection.query('SELECT * FROM `books` WHERE `author` = ?', ['David'], function (error, results, fields) {
  // error will be an Error if one occurred during the query
  // results will contain the results of the query
  // fields will contain information about the returned results fields (if any)
});

第二种,对象传参


connection.query({
  sql: 'SELECT * FROM `books` WHERE `author` = ?',
  timeout: 40000, // 40s
  values: ['David']
}, function (error, results, fields) {
  // error will be an Error if one occurred during the query
  // results will contain the results of the query
  // fields will contain information about the returned results fields (if any)
});

第三种,对象参数,数组结构


connection.query({
    sql: 'SELECT * FROM `books` WHERE `author` = ?',
    timeout: 40000, // 40s
  },
  ['David'],
  function (error, results, fields) {
    // error will be an Error if one occurred during the query
    // results will contain the results of the query
    // fields will contain information about the returned results fields (if any)
  }
);

第四种,字符串拼接,省略数组符号


connection.query(
  'SELECT * FROM `books` WHERE `author` = ?',
  'David',
  function (error, results, fields) {
    // error will be an Error if one occurred during the query
    // results will contain the results of the query
    // fields will contain information about the returned results fields (if any)
  }
);

结语

mysql依赖包内还有很多可以使用的集成方法,因时间问题,现更新至此,后续再继续编辑完善。

相关文章

Oracle如何使用授予和撤销权限的语法和示例
Awesome Project: 探索 MatrixOrigin 云原生分布式数据库
下载丨66页PDF,云和恩墨技术通讯(2024年7月刊)
社区版oceanbase安装
Oracle 导出CSV工具-sqluldr2
ETL数据集成丨快速将MySQL数据迁移至Doris数据库

发布评论