我想从 node.js 服务器创建 sql 表。但是,我遇到此错误:
(节点:13560)UnhandledPromiseRejectionWarning:错误:ER_NO_DB_ERROR:未选择数据库
我尝试添加:使用stan_sehk; 其中stan_sehk是模式的名称。但是我得到另一个错误: (节点:12468)UnhandledPromiseRejectionWarning:错误:ER_PARSE_ERROR:您的SQL语法有错误;
问题是select语句起作用,但create语句给出错误。 创建视图故事也是如此。
//MY db_config.json file
{
"mysql":{
"host": "localhost",
"port": 3306,
"acquireTimeout": 30000,
"user": "appuser",
"password" : "abc123",
"database": ""
},
"redis":{
"port" : 6379,
"host" : "127.0.0.1"
}
}
//我的mysql_access.js文件
const mysql = require('mysql');
const fs = require('fs');
const json = require('json');
const config_param = fs.readFileSync('./data_access/db_config.json', 'utf-8');
const config_param_json = JSON.parse(config_param);
const pool = mysql.createPool({
host: config_param_json.mysql.host,
port: config_param_json.mysql.port,
acquireTimeout: config_param_json.mysql.acquireTimeout,
user: config_param_json.mysql.user,
password: config_param_json.mysql.password,
dateStrings: true
});
let query = function( sql, values) {
return new Promise(( resolve, reject ) => {
pool.getConnection(function(err, connection) {
if (err) {
reject( err )
} else {
connection.query(sql, values, ( err, rows) => {
if ( err ) {
reject( err )
} else {
resolve(JSON.parse(JSON.stringify(rows)))
}
connection.release()
})
}
})
})
};
module.exports = {query};
查询错误1:
let sql = `create table if not exists todos(
id int primary key auto_increment,
title varchar(255)not null,
completed tinyint(1) not null default 0
)`;
let sql_call = {
sql: sql,
sql_value: null
};
let sql_result = await mysql_access.query(sql_call.sql, sql_call.sql_value);
console.log(sql_result[11]);
错误消息:
(node:10640) UnhandledPromiseRejectionWarning: Error: ER_NO_DB_ERROR: No database selected
查询错误2:
let sql = `use stan_sehk; create table if not exists todos(
id int primary key auto_increment,
title varchar(255)not null,
completed tinyint(1) not null default 0
)`;
let sql_call = {
sql: sql,
sql_value: null
};
let sql_result = await mysql_access.query(sql_call.sql, sql_call.sql_value);
console.log(sql_result[11]);
错误消息:
(node:12468) UnhandledPromiseRejectionWarning: Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'create table if not exists todos(id int primary key a' at line 1
如果我做的事情不正确,请帮助我。正如我说的那样, SELECT 查询可以工作,但是 CREATE 查询会出现上述错误。提前谢谢。