• 597 node之mysql2


    认识mysql2


    使用mysql2


    Prepared Statement(预编译语句)


    Connection Pools


    Promise方式


    01_mysql2的基本使用.js

    const mysql = require('mysql2');
    
    // 1.创建数据库连接
    const connection = mysql.createConnection({
      host: 'localhost',
      port: 3306,
      database: 'coderhub',
      user: 'root',
      password: 'Coderwhy888.'
    });
    
    // 2.执行SQL语句
    const statement = `
      SELECT * FROM products WHERE price > 6000;
    `
    connection.query(statement, (err, results, fields) => {
      console.log(results);
    });
    

    02_预处理语句.js

    const mysql = require('mysql2');
    
    // 1.创建数据库连接
    const connection = mysql.createConnection({
      host: 'localhost',
      port: 3306,
      database: 'coderhub',
      user: 'root',
      password: 'Coderwhy888.'
    });
    
    // 2.执行SQL语句
    // 在真正执行时会给?提供实际的参数才会执行
    const statement = `
      SELECT * FROM products WHERE price > ? AND score > ?;
    `
    connection.execute(statement, [6000, 7], (err, results) => {
      console.log(results);
    });
    

    03_连接池的使用.js

    const mysql = require('mysql2');
    
    // 1.创建连接池
    const connections = mysql.createPool({
      host: 'localhost',
      port: 3306,
      database: 'coderhub',
      user: 'root',
      password: 'Coderwhy888.',
      connectionLimit: 10
    });
    
    // 2.使用连接池
    const statement = `
      SELECT * FROM products WHERE price > ? AND score > ?;
    `
    connections.execute(statement, [6000, 7], (err, results) => {
      console.log(results);
    });
    
    

    04_promise的方式.js

    const mysql = require('mysql2');
    
    // 1.创建连接池
    const connections = mysql.createPool({
      host: 'localhost',
      port: 3306,
      database: 'coderhub',
      user: 'root',
      password: 'Coderwhy888.',
      connectionLimit: 10
    });
    
    // 2.使用连接池
    const statement = `
      SELECT * FROM products WHERE price > ? AND score > ?;
    `
    connections.promise().execute(statement, [6000, 7]).then(([results]) => {
      console.log(results);
    }).catch(err => {
      console.log(err);
    });
    
    

  • 相关阅读:
    第2课 有符号与无符号
    第1课 基本数据类型
    HDU 5821 Ball
    Codeforces Round #228 (Div. 2) C. Fox and Box Accumulation
    HDU 5810 Balls and Boxes
    HDU 5818 Joint Stacks
    HDU 5813 Elegant Construction
    Codeforces Round #357 (Div. 2)C. Heap Operations
    Codeforces Round #364 (Div. 2) C. They Are Everywhere
    HDU5806 NanoApe Loves Sequence Ⅱ
  • 原文地址:https://www.cnblogs.com/jianjie/p/14353775.html
Copyright © 2020-2023  润新知