How to use the mysql2/promise.createConnection function in mysql2

To help you get started, we’ve selected a few mysql2 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github compose-grandtour / node / example-mysql / server.js View on Github external
});

// Read from the database when the page is loaded or after a word is successfully added
// Use the getWords function to get a list of words and definitions from the database
app.get("/words", function(request, response) {
  getWords()
    .then(function(words) {
      response.send(words);
    })
    .catch(function(err) {
      console.log(err);
      response.status(500).send(err);
    });
});

mysql
  .createConnection(options)
  .then(conn => {
    connection = conn;
    return connection.query(
      "CREATE TABLE IF NOT EXISTS words (id int auto_increment primary key, word varchar(256) NOT NULL, definition varchar(256) NOT NULL)"
    );
  })
  .then(result => {
    // Listen for a connection.
    app.listen(port, function() {
      console.log("Server is listening on port " + port);
    });
  })
  .catch(err => {
    console.log(err);
    process.exit(1);
github systemaccounting / mxfactorial / schema / index.js View on Github external
exports.handler = async (event) => {
  const cmd = event.command
  const BRANCH = event.branch ? event.branch : 'develop'

  // clone repo using https://github.com/lambci/git-lambda-layer
  // configure 10s timeout on lambda
  await exec(`rm -rf /tmp/*`)
  await exec(`cd /tmp && git clone --depth 1 --single-branch --branch ${BRANCH} ${REPO}`)
  const { stdout, stderr } = await exec(`ls ${WRITABLE_LAMBDA_PATH}`)
  console.log('diffs found: ' + stdout.replace('\n', ' '))

  await mysql.createConnection(
    {
      host: DB_HOST,
      user: DB_USERNAME,
      password: DB_PASSWORD
    }
  ).then(connection => {
    connection.query(`CREATE DATABASE IF NOT EXISTS ${DB_NAME};`)
  })

  const sequelize = new Sequelize(DB_NAME, DB_USERNAME, DB_PASSWORD, {
    host: DB_HOST,
    logging: console.log,
    port: 3306,
    dialect: 'mysql',
    pool: {
      min: 0,
github scscms / scs-monitor / server / api.js View on Github external
async function deleteUser(ctx) {
  const data = ctx.request.body
  let ids = data.ids
  let msg
  if (/^\d+(,\d+)*$/.test(ids)) {
    const arr = ids.split(',')
    const connection = await mysql.createConnection(config.mysqlDB)
    const [result] = await connection.execute(`DELETE from user where user_type<>1 and user_type<>2 and id in (${arr.map(() => '?').join(',')})`, arr)
    msg = result.affectedRows > 0 ? '' : '删除用户失败!'
    await connection.end()
  } else {
    msg = 'ID参数不合法'
  }
  ctx.body = {
    success: !msg,
    message: msg,
    data: {}
  }
}
// 用户上传头像
github scscms / scs-monitor / server / api.js View on Github external
if (data.sort_id) {
    querying += ' and code = ?'
    arr.push(data.sort_id)
  }
  let reg = /^\d{4}-\d{1,2}-\d{1,2}$/
  if (reg.test(begin) && reg.test(end)) {
    if (begin === end) {
      querying += ' and to_days(occurrence) = to_days(?)'
      arr.push(begin)
    } else {
      querying += ' and occurrence BETWEEN ? AND ?'
      arr.push(begin, end)
    }
  }
  querying = querying.replace('and', 'where')
  const connection = await mysql.createConnection(config.mysqlDB)
  const [rows] = await connection.execute(`SELECT SQL_NO_CACHE COUNT(*) as total FROM ${table} ${querying}`, arr)
  const total = rows[0].total// 总数量
  const pages = Math.ceil(total / pageSize)
  if (page > pages) {
    page = Math.max(1, pages)// 以防没数据
  }
  querying += ' ORDER BY id DESC LIMIT ?, ?'
  arr.push((page - 1) * pageSize, pageSize)
  const [list] = await connection.execute(`SELECT * FROM ${table} ${querying}`, arr)
  await connection.end()
  ctx.body = {
    success: true,
    message: '',
    data: {
      page, total, data: list
    }
github scscms / scs-monitor / server / api.js View on Github external
async function saveReport(column, value, values, code, referer) {
  // 连接数据库前先判断是否合法及抽样
  let row = 0
  let obj = common.project_list.find(arr => arr.code === code)
  let odds = values === 'performance' ? 'performance_odds' : 'log_odds'
  if (obj && referer.includes(obj.domain) && obj[odds] > Math.random()) {
    const connection = await mysql.createConnection(config.mysqlDB)
    if (values === 'performance') {
      const [result] = await connection.execute(`INSERT INTO performance (${column.join(',')}) VALUES (${column.map(() => '?').join(',')})`, value)
      row = result.affectedRows
    } else if (Array.isArray(values)) {
      const [result] = await connection.execute(`INSERT INTO reports (${column.join(',')}) VALUES ${value.join(',')}`, values)
      row = result.affectedRows
    }
    await connection.end()
  }
  return row
}
// 管理员删除上报信息\性能信息
github scscms / scs-monitor / server / api.js View on Github external
async function privateGetProject() {
  const connection = await mysql.createConnection(config.mysqlDB)
  const [list] = await connection.execute(`select * from project order by sort`, [])
  await connection.end()
  common.project_list = list
}
// 项目列表
github gnemtsov / ab-app / backend / core / db.js View on Github external
'use strict';

const mysql = require('mysql2/promise');

//database connection
if (typeof DBC === 'undefined' || DBC === null) {
    var DBC = mysql.createConnection({
        host: process.env.DB_HOST,
        user: process.env.DB_USER,
        password: process.env.DB_PASSWORD,
        database: process.env.DB_NAME
    });
}

DBC.getInsertQuery = (tableName, cols, data, onDuplicate) => {
    //TODO onDuplicate
    return {
        sql: `
            INSERT into ${tableName} (${cols.join(', ')}) 
            VALUES (${cols.map(col => '?').join(', ')})
        `,
        params: cols.map(col => data[col])
    }
github generaptr / generaptr / src / handlers / mysql / Handler.ts View on Github external
private async connect(): Promise {
    const connection: mysql.Connection = await mysql.createConnection({
      ...this.options,
      database: 'information_schema',
    });

    this.connection = connection;
    
    return true;
  }
github bradzacher / mysqldump / src / DB.ts View on Github external
public static async connect(options: mysql.IConnectionConfig): Promise {
        const instance = new DB(await mysql.createConnection(options));
        pool.push(instance);

        return instance;
    }
github reimagined / resolve / packages / adapters / snapshot-adapters / resolve-snapshot-mysql / src / index.js View on Github external
pool.connectPromise = (async () => {
    const { bucketSize, tableName, ...connectionOptions } = pool.config
    pool.connection = await MySQL.createConnection(connectionOptions)
    pool.bucketSize = bucketSize
    if (!Number.isInteger(pool.bucketSize) || pool.bucketSize < 1) {
      pool.bucketSize = DEFAULT_BUCKET_SIZE
    }
    pool.tableName = tableName
    if (pool.tableName == null || pool.tableName.constructor !== String) {
      pool.tableName = DEFAULT_TABLE_NAME
    }

    pool.counters = new Map()
  })()