node使用原生方式,连接mysql数据库

(async () => {
    // 链接数据库
    const mysql = require('mysql2/promise');    // npm i mysql2
    const cfg = {
        host: 'localhost',
        user: 'root',
        password: ';he%0f_,ljyW',
        database: 'izengx',
    }
    const connection = await mysql.createConnection(cfg);
    
    // 创建一个新表tests
    let ret = await connection.execute(`CREATE TABLE IF NOT EXISTS tests (
        id INT NOT NULL AUTO_INCREMENT,
        message VARCHAR(45) NULL,
        PRIMARY KEY (id)
    )`)
    console.log('create', ret);
    
    // 新建数据
    ret = await connection.execute(`INSERT INTO tests(message) VALUE(?)`, ['newData'])
    console.log('新建数据', ret);
    
    const [rows, fields] = await connection.execute(`
        SELECT * FROM tests
    `)
    console.log('查询数据', rows);
    
})()

你可能感兴趣的:(node.js,mysql)