Node. js notes (4) mysql database operations, node. jsmysql

Source: Internet
Author: User

Node. js notes (4) mysql database operations, node. jsmysql

This article does not fully refer to Chapter 11th of the Node Learning Guide.
For more information, see
Http://www.crifan.com/node_js_run_mysql_createclient_error_typeerror_object_has_no_method_createclient/
Thanks for his code
--------------------------
In the second article, the database is successfully connected, and you are ready to add, delete, modify, and query data.
The code in the connection method is as follows:

Create a connection var client = mysql. createClient ({user: 'root', password: 'rainbow ',});

This connection code will report an error. You should use the createConnection method.
Specify the host

var connection = mysql.createConnection({    host : 'localhost',    user : 'root',    password : '194910'});

Declare Variables

var TEST_DATABASE = 'mydb';var TEST_TABLE = 'test';

Create a database

connection.query('CREATE DATABASE '+TEST_DATABASE, function(err) {  if (err && err.number != mysql.ERROR_DB_CREATE_EXISTS) {    throw err;  }});

Declared database:

connection.query('USE '+TEST_DATABASE);

Create a new table

connection.query(  'CREATE TABLE '+TEST_TABLE+  '(id INT(11) AUTO_INCREMENT, '+  'name VARCHAR(255), '+  'PRIMARY KEY (id))');

Insert a record

connection.query(  'INSERT INTO '+TEST_TABLE+' '+  'SET name = ?',  ['hello']);

Note that there is a space before the quotation marks of 'insert '.

Query:

connection.query(  'SELECT * FROM '+TEST_TABLE,  function selectCb(err, results, fields) {    if (err) {      throw err;    }    console.log(results);    console.log(fields);    connection.end();  });

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.