在节点js中,我有非常简单的代码来向数据库发出请求:
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'user',
password: 'password',
database: "databasename"
});
connection.connect();
connection.query('SELECT * FROM main_categories', function (error, results, fields) {
if (error) throw error;
console.log(results);
});
connection.end();
我用这个sql脚本创建数据库和表:
CREATE DATABASE databasename
CHARACTER SET utf8
COLLATE utf8_unicode_ci;
CREATE TABLE main_categories (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
当我试图在mysql控制台中选择代码时,一切看起来都不错,但是当我试图在node.js中获得结果时,在控制台日志中我看到它是这样的:
[ RowDataPacket { id: 1, name: 'Візочки' },
RowDataPacket { id: 2, name: 'ДитÑчий транÑпорт' },
RowDataPacket { id: 3, name: 'ÐвтокріÑла' },
RowDataPacket { id: 4, name: 'Іграшки' },
RowDataPacket { id: 5, name: 'ДитÑча кімната' },
RowDataPacket { id: 6, name: 'Ð’Ñе Ð´Ð»Ñ Ð³Ð¾Ð´ÑƒÐ²Ð°Ð½Ð½Ñ' },
RowDataPacket { id: 7, name: 'ÐкÑеÑуари Ð´Ð»Ñ Ð¼Ð°Ð¼' },
RowDataPacket { id: 8, name: 'Гігієна та доглÑд' } ]
在使用charset
和任何其他解决方案时,我尝试在配置对象中添加mysql.createConnection
,但遗憾的是没有结果。
UPD:查看数据库变量可能会有所帮助:
mysql> SHOW variables WHERE variable_name LIKE '%coll%' OR variable_name LIKE '%char%';
+--------------------------+-----------------------------------------------------------+
| Variable_name | Value |
+--------------------------+-----------------------------------------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | latin1 |
| character_set_system | utf8 |
| character_sets_dir | /usr/local/mysql-5.7.19-macos10.12-x86_64/share/charsets/ |
| collation_connection | utf8_general_ci |
| collation_database | utf8_general_ci |
| collation_server | latin1_swedish_ci |
+--------------------------+-----------------------------------------------------------+
答案 0 :(得分:1)
Візочки
, Візочки
为Mojibake。当你到处都没有utf8 / utf8mb4时会发生这种情况。特别是,node.js需要像
var connection = mysql.createConnection({ ... , charset : 'utf8mb4'});
答案 1 :(得分:0)
我在创建表格之前添加了SET NAMES utf8;
,因此它看起来像这样:
SET NAMES utf8;
CREATE TABLE main_categories (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
那就是它!