nodejs创建mysql数据库表

nodejs创建mysql数据库表

const mysql = require('mysql');

// 创建数据库连接
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'your_username',
  password: 'your_password',
  database: 'your_database'
});

// 连接数据库
connection.connect((err) => {
  if (err) throw err;
  console.log('Connected to MySQL database.');
});

// 创建数据表
const createTableSql = `
  CREATE TABLE IF NOT EXISTS users (
    id INT(11) NOT NULL AUTO_INCREMENT,
    username VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL,
    password VARCHAR(100) NOT NULL,
    isActive BOOLEAN NOT NULL DEFAULT true,
    createdAt DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updatedAt DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id)
  )
`;

connection.query(createTableSql, (err, result) => {
  if (err) throw err;
  console.log('Table users created.');
});

// 关闭数据库连接
connection.end();

你可能感兴趣的:(数据库,mysql)