小码哥的IT人生

Python MySQL Drop Table

Python基础 2022-06-06 12:58:23小码哥的IT人生shichen

Python MySQL Drop Table

删除表

您可以使用 "DROP TABLE" 语句来删除已有的表:

示例代码:

删除 "customers" 表:

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  passwd="yourpassword",
  database="mydatabase"
)
mycursor = mydb.cursor()
sql = "DROP TABLE customers"
mycursor.execute(sql)

完整实例:

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="myusername",
  passwd="mypassword",
  database="mydatabase"
)
mycursor = mydb.cursor()
sql = "DROP TABLE customers"
mycursor.execute(sql)
#If this page was executed with no error(s), you have successfully deleted the "customers" table.

只在表存在时删除

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

示例代码:

删除表 "customers" (如果存在):

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  passwd="yourpassword",
  database="mydatabase"
)
mycursor = mydb.cursor()
sql = "DROP TABLE IF EXISTS customers"
mycursor.execute(sql)

完整实例:

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="myusername",
  passwd="mypassword",
  database="mydatabase"
)
mycursor = mydb.cursor()
sql = "DROP TABLE IF EXISTS customers"
mycursor.execute(sql)
#If this page was executed with no error(s), you have successfully deleted the "customers" table.

版权所有 © 小码哥的IT人生
Copyright © phpcodeweb All Rights Reserved
ICP备案号:苏ICP备17019232号-2  

苏公网安备 32030202000762号

© 2021-2024