简体   繁体   中英

Node js in not saving data in MySql database

I have the following code. When i execute it, i get

Database connected successfully. 1 record inserted. But it saves no data in MySql database, Im pretty sure my code is correct? but do someone has any tip or advice?

var mysql = require('mysql');

var dbconn = mysql.createConnection({
   host: "localhost",
   user: "root",
   password: "",
   database: "assessment"
});
dbconn.connect(function(err) {
   if (err) throw err;
   console.log("Database connected successfully!");

  var sqlquery = "INSERT INTO users (username,password) VALUES ('john', 'jmpleom')";
  dbconn.query(sqlquery, function (err, result) {
    if (err) throw err;
        console.log(result.affectedRows + " record inserted");
  });
});

Have you tried committing the data to the database? As a failsafe from unfinished queries, databases will rollback any records to their original state if the data is not committed to the database.

After your insert query, try it out. Based on your code it might look something like this:

  dbconn.commit(function(err) {
        if (err) { 
          connection.rollback(function() {
            throw err;
          });

To save or commit data you have to end the connection like this:

dbconn.connect(function(err) {
if (err) throw err;
console.log("Database connected successfully!");

var sqlquery = "INSERT INTO users (username,password) VALUES('john','jmpleom')";
dbconn.query(sqlquery, function (err, result) {
if (err) throw err;
    console.log(result.affectedRows + " record inserted");
    dbconn.end(); //like this
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM