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 删除表


删除表

您可以使用 "DROP TABLE" 语句删除现有表

示例

删除表 "customers"

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});

con.connect(function(err) {
  if (err) throw err;
  var sql = "DROP TABLE customers";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("表已删除");
  });
});
运行示例 »

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

运行 "demo_db_drop_table.js"

C:\Users\Your Name>node demo_db_drop_table.js

这将为您提供以下结果

表已删除


仅在存在时删除

如果您要删除的表已被删除,或由于任何其他原因不存在,您可以使用 IF EXISTS 关键字来避免出现错误。

示例

如果存在,则删除表 "customers"

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});

con.connect(function(err) {
  if (err) throw err;
  var sql = "DROP TABLE IF EXISTS customers";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log(result);
  });
});
运行示例 »

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

运行 "demo_db_drop_table_if.js"

C:\Users\Your Name>node demo_db_drop_table_if.js

如果表存在,结果对象将如下所示

{
  fieldCount: 0,
  affectedRows: 0,
  insertId: 0,
  serverstatus: 2,
  warningCount: 0,
  message: '',
  protocol41: true,
  changedRows: 0
}

如果表不存在,结果对象将如下所示

{
  fieldCount: 0,
  affectedRows: 0,
  insertId: 0,
  serverstatus: 2,
  warningCount: 1,
  message: '',
  protocol41: true,
  changedRows: 0
}

如您所见,如果表不存在,唯一的区别是 warningCount 属性被设置为 1。


×

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.