UNPKG

2.36 kBMarkdownView Raw
1# think-mysql
2[![Build Status](https://travis-ci.org/thinkjs/think-mysql.svg?branch=master)](https://travis-ci.org/thinkjs/think-mysql)
3[![Coverage Status](https://coveralls.io/repos/github/thinkjs/think-mysql/badge.svg?branch=master)](https://coveralls.io/github/thinkjs/think-mysql?branch=master)
4[![npm](https://img.shields.io/npm/v/think-mysql.svg?style=flat-square)](https://www.npmjs.com/package/think-mysql)
5
6## Install
7
8```
9npm install think-mysql
10```
11
12## How to use
13
14### default options
15
16You can find all the config options at https://github.com/mysqljs/mysql#connection-options
17
18```js
19const defaultConfig = {
20 port: 3306,
21 host: '127.0.0.1',
22 user: '',
23 password: '',
24 database: '',
25 connectionLimit: 1,
26 multipleStatements: true,
27 logger: console.log.bind(console),
28 logConnect: false,
29 logSql: false,
30 acquireWaitTimeout: 0 // if set timeout, it will be throw an error after get connection timeout
31};
32```
33
34### Usage
35
36#### Custom usage
37```js
38 import mysql from 'think-mysql';
39 let instance = mysql.getInstance(config);
40 await instance.execute({
41 sql:"insert into `think_test`.`books` (`name`, `author`) values ('thinkjs best practice', ?)",
42 timeout: 5000,
43 values: ['David']
44 });
45 let books = await instance.query({
46 sql:'SELECT * FROM `books` WHERE `author` = ?',
47 timeout: 5000,
48 values: ['David']
49 });
50 console.log(books[0].name) //thinkjs best practice
51```
52
53#### Transactions
54
55```js
56 import mysql from 'think-mysql';
57 let instance = mysql.getInstance(config);
58 let result = null;
59 try{
60 await instance.transaction(async(conn) => {
61 result = instance.execute({
62 sql: "insert into `think_test`.`books` (`name`, `author`) values ('1st step', ?)",
63 values: ['0-David']
64 }, conn);
65 result = await instance.execute({
66 sql: "insert into `think_test`.`books` (`name`, `author`) values ('2nd step', ?)",
67 values: [`${result.insertId}-David`]
68 }, conn);
69 await instance.execute({
70 sql: "insert into `think_test`.`books` (`name`, `autor`) values ('3rd step', ?)",
71 values: [`${result.insertId}-David`]
72 }, conn);
73 });
74 }catch (e){
75 console.log(e);
76 }
77 result = await instance.query({
78 sql:'SELECT * FROM `books` WHERE `author` = ?',
79 values:[`${result.insertId}-David`]
80 });
81 console.log(result[0].name); //3rd step
82```
\No newline at end of file