Nodejs+mysql, linking MySQL processing data enforces the use of UTF-8 encoding to avoid garbled characters.

Source: Internet
Author: User

The steps are as follows:

1. Set the connection properties to allow multiple SQL statements:

Multiplestatements:true

Const POOL = Mysql.createpool ({    $,    ' localhost ',    ' root ',    ' * * * ',    ' DatabaseName ',
DatabaseName do not use uppercase, otherwise the database cannot be found. (Uppercase auto-turn lowercase is supported under windows, only lowercase is supported under Linux) true });

2. Add "SET NAMES ' UTF8" before the SQL statement; "To set the link, platform, result encoding form

3. When the callback function is called, apply (null,arguments) instead of apply (Null,[err,results[1],fields])

//take the Insert data as an examplefunctioninsertsql (table, obj, callback) {Let sqlstr= ""; Let names= []; Let values= []; if(_.isempty (obj)) {sqlstr=' INSERT into ${table} VALUES () '; } Else {         for(Let datainchobj)            {Names.push (data.tostring ());        Values.push (Obj[data].tostring ()); } sqlstr= ' INSERT into ${table} (${names.join (', ')}) VALUES (${' "' + values.join ('", "') + '" '})`;    } console.log (SQLSTR); Pool.getconnection (function(err, connection) {//Use the connectionConnection.query ("SET NAMES ' UTF8 ';" + sqlstr,function(Err, results, fields) {//And done with the connection.connection.release (); //Don ' t use the connection here, it had been returned to the pool.Callback.apply (NULL, [err,results[1],fields]);    }); });}

Nodejs+mysql, linking MySQL processing data enforces the use of UTF-8 encoding to avoid garbled characters.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.