Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

node.js中mysql数据化初始化、表、查询 #16

Open
gaowei1012 opened this issue Jul 11, 2020 · 3 comments
Open

node.js中mysql数据化初始化、表、查询 #16

gaowei1012 opened this issue Jul 11, 2020 · 3 comments

Comments

@gaowei1012
Copy link
Owner

初始化数据库

const mysql = require('mysql')
const {database} = require('../config/default') // 数据库配置

// create Pool
const pool = mysql.createPool({
    host        :   database.HOST,
    user        :   database.USERNAME,
    password    :   database.PASSWORD,
    database    :   database.DATABASE,
    port        :   database.PORT
})

// 查询语句
const query = (sql, values) => {
    return new Promise((resolve, reject) => {
        pool.getConnection((err, connection) => {
            if (err) {
                reject(err)
            } else {
                connection.query(sql, values, (err, rows) => {
                    if (err) {
                        reject(err)
                    } else {
                        resolve(rows)
                    }
                    connection.release()
                })
            }
        })
    })
}
@gaowei1012
Copy link
Owner Author

gaowei1012 commented Jul 11, 2020

创建表结构

// 设置中文 character set = utf8;

const users = `
    create table if not exists users(
        id INT NOT NULL AUTO_INCREMENT,
        username VARCHAR(100) NOT NULL COMMENT '用户名',
        password VARCHAR(100) NOT NULL COMMENT '用户密码',
        mobile VARCHAR(100) NOT NULL COMMENT '手机号',
        avatar VARCHAR(100) NOT NULL COMMENT '用户头像',
        create_at VARCHAR(100) NOT NULL COMMENT '用户创建时间',
        PRIMARY KEY(id)
    ) character set = utf8;;
`

@gaowei1012
Copy link
Owner Author

// 创建表

  const createTable = (sql) => {
    return query(sql, [])
  }

// 建表
createTable(users)

@gaowei1012
Copy link
Owner Author

// 查询语句

  // 用户注册
exports.insterUserData = (val) => {
    console.log('val', val)
    const _sql = "insert into users set username=?,password=?,mobile=?,avatar=?,create_at=?;"
    return query(_sql, val)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant