1.mysql and Promise-mysql
Nodejs connection MySQL has a mature npm package MySQL, if required promise, recommended to use Promise-mysql;
Npm:https://www.npmjs.com/package/mysql
Https://www.npmjs.com/package/promised-mysql
In the actual development, the individual connection does not satisfy the business need, needs to use the connection pool to make the connection the establishment and the release, the Promise-mysql establishment connection pool is very simple:
1Const CONFIG = {2Host: ' XXXxxx ',//IP also line domain name also line3User: ' Root ',4Password: ' 123456 ',5Connectionlimit:30,6Database: ' movie ',//Database7Port: ' 8306 '8 };9 //establishing a connection poolTenConst POOL =mysql.createpool (config); One //Execute SQL using pool.query Quick connect APool.query (' xxxx ')); - - //build a connection to automatically release resources using USING/DISPSOER mode the functiongetsqlconnection () { - returnPool.getconnection (). Disposer ((c) ={ - pool.releaseconnection (c); - }); + } - //need to use Bluebird to encapsulate promise objects with dispsoer functionality + functionquery (SQL) { A returnPromise.using (Getsqlconnection (), (con) ={ at returnSql?con.query (sql): con; - }) -}
Through the promise package for MySQL connection, we can use Async/await mode for enjoyable programming
2. Performing Transactions through Promise-mysql
The BeginTransaction, commit, and rollback of connection objects can be implemented
1AsyncfunctionExecaffairs () {2Console.log (' Begin Execaffairs ');3 //Write Transactions4Const CONN =await query ();5await Conn.begintransaction ();//begin;6 Try{7Await Conn.query (' select * from Movie_detail where m_id=242167 for update ');8Await conn.query (' Update movie_detail set m_record=7.5 where m_id=242167 ');9await Conn.commit ();//CommitTenConsole.log (' Commit complete '); One}Catch(e) { AConsole.log (' Transaction error '), e); - await Conn.rollback (); - } the /****** - //No release required - finally{ - conn.release (); + } - */ +}
Because this example uses Promise-mysql's disposer mode, no additional processing of the connected release
For related codes, see: HTTPS://GITHUB.COM/JHONELEE/NODESCHEDULEMYSQL
Nodejs Graceful connection to MySQL