MySql connection
MySql installation modules:
npm install mysql
Create a connection:
. 1 const = mysql the require ( 'mysql' ) 2 . 3 // connect mysql server . 4 const = Connection mysql.createConnection ({ . 5 Host: '127.0.0.1' , . 6 User: 'the root', // the user name to access the database 7 password: '123456', // database access password . 8 port: '3306', // database port number . 9 database: 'XXX', // name of the database 10 }) 11 // execute the SQL 12 is connection.query (SQL, function (ERR, Result) { 13 is ERR //Error message 14 the Result // result 15 }) 16 // destroy a connection | Because JS is asynchronous, so the current code before executing the SQL connections were destroyed 17 connection.destroy ()
Mysql create a connection createConnection, Each time a new connection is connection.query will cause a great waste of resources, reduce performance.
Connection pooling is another method of performing, it created a number of one-time connection, and then according to the client's queries, automatic distribution, reuse, manage these connections.
. 1 const = MySQL the require ( 'MySQL' ) 2 . 3 // Create a connection pool . 4 const the pool = mysql.createPool ({ . 5 Host: '127.0.0.1' , . 6 User: 'the root', // the user name to access the database 7 password: '123456', // database access password . 8 port: '3306', // database port number . 9 database: 'XXX', // name of the database 10 }) . 11 12 is const DB = { 13 is sqlQuery (SQL, values ) { 14 return new new Promise ((Resolve, Reject) => { 15 pool.getConnection((err, connection) => { 16 if (err) { 17 reject(err) 18 } else { 19 if (values) { 20 connection.query(sql, values, (err, rows) => { 21 if (err) { 22 reject(err) 23 } else { 24 resolve(rows) 25 } 26 connection.release() 27 }); 28 } else { 29 connection.query(sql, (err, rows) => { 30 if (err) { 31 reject(err) 32 } else { 33 resolve(rows) 34 } 35 connection.release() 36 }); 37 } 38 } 39 }) 40 }) 41 } 42 }
? MySql query variable with a number as a placeholder (to prevent SQL injection):
1 var query = 'UPDATE users SET foo = ?, bar = ?, baz = ? WHERE id = ?', 2 value = ['a', 'b', 'c', userId]; 3 connection.query(query, value, (error, results, fields) => { /* ... */ });
The first parameter is a query string, the query is sql statement contains placeholders.
The second parameter value is an array containing all values placeholder.
Identifiers (database, table, column names) with two numbers as a placeholder (ie ??), in addition to the identifier name can be passed as query variables together into a list of values?:
1 var query = 'UPDATE ?? SET foo = ?, bar = ?, baz = ? WHERE id = ?', 2 value = ['users', 'a', 'b', 'c', userId]; 3 connection.query(query, value, (error, results, fields) => { /* ... */ });