Node.js在MySQL做增删改查
mysql
Node.js可以使用mysql
这个库来操作MySQL数据库,基本的增删改查都支持。
const mysql = require('mysql');
require('dotenv').config();
var connection = mysql.createConnection({
host : 'xxx.xx.xxx.187',
port : '13306',
user : 'root',
password : process.env.MYSQL_PASSWORD,
database : 'ethbtc'
});
connection.connect();
var sql = 'select * from ethbtc.t_kline_1m limit 1 ';
var insert_sql = 'insert into ethbtc.t_kline_1m(open_time, open_price, high_price, low_price, close_price ,volume, close_time, quote_volume, count, taker_buy_volume, taker_buy_quote_volume, ignore0) values(?,?,?,?,?,?,?,?,?,?,?,?)';
var insert_params = [1723793791255, 0.07543, 0.07543, 0.07543, 0.07543, 67.7454, 1723793791255, 5.10983166, 64, 28.3816, 28.3816, '0'];
var resultHandler = function(error, result, fields){
if(error) throw error;
console.log(result[0].close_price);
//console.log(fields);
}
//查询
connection.query(sql, resultHandler);
//新增
connection.query(insert_sql, insert_params, function(err, result){
if(err){
console.log('[INSERT ERROR] - ',err.message);
return;
}
console.log('--------------------------INSERT----------------------------');
//console.log('INSERT ID:',result.insertId);
console.log('INSERT ID:',result);
console.log('-----------------------------------------------------------------\n\n');
});
connection.end();
运行node .\crud_mysql.js
:
node .\crud_mysql.js
0.075439
--------------------------INSERT----------------------------
INSERT ID: OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}
-----------------------------------------------------------------