VPN技术 · 2023年11月10日 0

使用Node.js创建MySQL数据库

Node.js MySQL Database Creation

Node.js – MySQL Database Creation

var mysql = require(mysql);
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword"
});
con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  con.query("CREATE DATABASE mydb", function (err, result) {
    if (err) throw err;
    console.log("MySQL database created successfully");
  });
});

Save the file as demo_node_mysql_create.js

Then run

npm demo_node_mysql_create.js 

The result will be:

MySQL database created successfully

When creating a table with primary key, you should also create a column with a unique key for each record. This can be done by defining a column as “INT AUTO_INCREMENT PRIMARY KEY”, which will insert a unique number for each record starting from 1 and incrementing by 1.

var mysql = require(mysql);
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});
con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  var sql = "CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("Table created");
  });
});

If the table already exists, you can use the ALTER TABLE keyword:

var mysql = require(mysql);
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});
con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  var sql = "ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("Table altered");
  });
});

To insert into a table, use the “INSERT INTO” statement in MySQL:

var mysql = require(mysql);
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});
con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  var sql = "INSERT INTO customers (name, address) VALUES (Company Inc, Highway 37)";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("1 record inserted");
  });
});

You can also insert multiple data at once:

var mysql = require(mysql);
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});
con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  var sql = "INSERT INTO customers (name, address) VALUES ?";
  var values = [
    [John, Highway 71],
    [Peter, Lowstreet 4],
    [Amy, Apple st 652],
    [Hannah, Mountain 21],
    [Michael, Valley 345],
    [Sandy, Ocean blvd 2],
    [Betty, Green Grass 1],
    [Richard, Sky st 331],
    [Susan, One way 98],
    [Vicky, Yellow Garden 2],
    [Ben, Park Lane 38],
    [William, Central st 954],
    [Chuck, Main Road 989],
    [Viola, Sideway 1633]
  ];
  con.query(sql, [values], function (err, result) {
    if (err) throw err;
    console.log("Number of records inserted: " + result.affectedRows);
  });
});

When executing a query, a result object is returned. The result object contains information about how the query has affected the table. From the above example, the result object returned is:

{ fieldCount: 0, affectedRows: 14, insertId: 0, serverStatus: 2, warningCount: 0, message: "Records:14 Duplicated: 0 Warnings: 0", protocol41: true, changedRows: 0 }

To get the inserted ID for a table with auto-incremented identifier field, you can ask the result object. Note: To be able to get the inserted id, only one row can be inserted.

var mysql = require(mysql);
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});
con.connect(function(err) {
  if (err) throw err;
  var sql = "INSERT INTO customers (name, address) VALUES (Michelle, Blue Village 1)";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("1 record inserted, ID: " + result.insertId);
  });
});

To select data from a table in MySQL, use the "SELECT" statement:

var mysql = require(mysql);
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});
con.connect(function(err) {
  if (err) throw err;
  con.query("SELECT * FROM customers", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
  });
});

To select only specific columns from a table, use the "SELECT" statement and the column names:

var mysql = require(mysql);
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});
con.connect(function(err) {
  if (err) throw err;
  con.query("SELECT name, address FROM customers", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
  });
});

The result object from the above example is an array containing each row as an object. To return, for example, the address of the third record, simply reference the address property of the third array object:

console.log(result[2].address);

The fields object is an array containing information about each field in the result. To return, for example, the name of the second field, simply reference the name property of the second array item:

console.log(fields[1].name);

To select records with a filter, use the "WHERE" statement:

var mysql = require(mysql);
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});
con.connect(function(err) {
  if (err) throw err;
  con.query("SELECT * FROM customers WHERE address = Park Lane 38", function (err, result) {
    if (err) throw err;
    console.log(result);
  });
});

You can also use wildcards to select records that start with, contain, or end with a given letter or phrase. Use the % wildcard to represent zero, one, or multiple characters:

var mysql = require(mysql);
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});
con.connect(function(err) {
  if (err) throw err;
  con.query("SELECT * FROM customers WHERE address LIKE S%", function (err, result) {
    if (err) throw err;
    console.log(result);
  });
});

To escape query values when the query value is a user-provided variable, you should escape the value. This is to prevent SQL injection, which is a common web hacking technique to destroy or abuse your database. The MySQL module has a method to escape query values:

var adr = "Mountain 21";
var sql = "SELECT * FROM customers WHERE address = " + mysql.escape(adr);
con.query(sql, function (err, result) {
  if (err) throw err;
  console.log(result);
});

You can also use a ? as a placeholder for the value you want to escape. In this case, the variable is sent as the second parameter in the query() method:

var adr = "Mountain 21";
var sql = "SELECT * FROM customers WHERE address = ?";
con.query(sql, [adr], function (err, result) {
  if (err) throw err;
  console.log(result);
});

If you have multiple placeholders, the array will contain multiple values in the order of the placeholders:

var name = "Amy";
var adr = "Mountain 21";
var sql = "SELECT * FROM customers WHERE name = ? OR address = ?";
con.query(sql, [name, adr], function (err, result) {
  if (err) throw err;
  console.log(result);
});