Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Node.js MySQL 创建表格


创建表格

为了在 MySQL 中创建表格,使用 "CREATE TABLE" 语句。

确保在创建连接时定义数据库名称

示例

创建一个名为 "customers" 的表格

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "你的用户名",
  password: "你的密码",
  database: "mydb"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("连接成功!");
  var sql = "CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("表格创建成功");
  });
});
运行示例 »

将上面的代码保存在名为 "demo_create_table.js" 的文件中,然后运行该文件

运行 "demo_create_table.js"

C:\Users\你的姓名>node demo_create_table.js

你将得到以下结果

连接成功!
表格创建成功


主键

在创建表格时,你应该为每条记录创建一列,该列具有唯一的键值。

这可以通过将一列定义为 "INT AUTO_INCREMENT PRIMARY KEY" 来实现,该操作将为每条记录插入一个唯一的数字。从 1 开始,每条记录递增 1。

示例

在创建表格时创建主键

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "你的用户名",
  password: "你的密码",
  database: "mydb"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("连接成功!");
  var sql = "CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("表格创建成功");
  });
});
运行示例 »

如果表格已存在,请使用 ALTER TABLE 关键字

示例

在现有表格上创建主键

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "你的用户名",
  password: "你的密码",
  database: "mydb"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("连接成功!");
  var sql = "ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("表格已更改");
  });
});
运行示例 »

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.