python删除mysql_Python MySQL-删除表

python删除mysql

In this tutorial, we will learn how to delete a MySQL table or drop the table completely from the database using Python.

在本教程中,我们将学习如何使用Python从数据库中删除MySQL表或将其完全删除

To completely delete an existing table(both table data and table itself), the DROP TABLE SQL statement is used.

要完全删除现有表 (表数据和表本身),请使用DROP TABLE SQL语句。

Python MySQL DROP TABLE :示例 (Python MySQL DROP TABLE: Example)

Let's assume we have a table with name customers in the studytonight database. Then we can use the below code to drop that table:

假设我们在studytonight数据库中有一个名称为customer的表。 然后,我们可以使用以下代码删除该表:

import mysql.connector as mysql

db = mysql.connect(
    host = "localhost",
    user = "yourusername",
    passwd = "yourpassword",
    database = "studytonight"
)

cursor = db.cursor()
## We have created another table in our database named customers  
## and now we are deleting it
sql = "DROP TABLE customers"

cursor.execute(sql)

If the above code will execute without any error it means table named customers is deleted succesfully.

如果上面的代码可以正确执行,则意味着成功删除了名为customers的表。

Python MySQL-删除表(如果存在) (Python MySQL - Drop Table if it exists)

The IF EXISTS keyword is used to avoid error which may occur if you try to drop a table which doesn't exist.

IF EXISTS关键字用于避免尝试删除不存在的表时可能发生的错误。

When we use the IF EXISTS clause, we are informing the SQL engine that if the given table name exists, then drop it, if it doesn't exists, then do nothing.

当我们使用IF EXISTS子句时,我们通知SQL引擎,如果给定的表名存在,则将其删除;如果不存在,则不执行任何操作。

import mysql.connector as mysql

db = mysql.connect(
    host = "localhost",
    user = "yourusername",
    passwd = "yourpassword",
    database = "studytonight"
)

cursor = db.cursor()

sql = "DROP TABLE IF EXISTS customers"

cursor.execute(sql)

If the code executes without an error, then it means the customers table is deleted if it existed.

如果代码执行没有错误,则意味着客户表(如果存在)被删除。

Here is the snapshot of the actual output:

这是实际输出的快照:

python mysql drop table output

So in this tutorial we learned how to drop a MySQL table using Python. This is useful when we have some application which creates some temporary tables to store some data and then after the processing, deletes those tables.

因此,在本教程中,我们学习了如何使用Python删除MySQL表。 当我们有一些应用程序创建一些临时表来存储一些数据,然后在处理之后删除这些表时,这很有用。

翻译自: https://www.studytonight.com/python/python-mysql-drop-table

python删除mysql

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值