ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

实现一个MYSQL工具类,包含判断创建数据表是否存在,创建数据表

2026/8/7 6:10:44 拓冰建站 浏览量
实现一个MYSQL工具类,包含判断创建数据表是否存在,创建数据表

可以使用Python的MySQLdb模块来实现一个MYSQL工具类。下面是一个简单的实现示例:

import MySQLdbclass MySQLTool:def __init__(self, host, user, password, database):self.host = hostself.user = userself.password = passwordself.database = databasedef connect(self):self.connection = MySQLdb.connect(host=self.host,user=self.user,password=self.password,database=self.database)self.cursor = self.connection.cursor()def table_exists(self, table_name):self.cursor.execute(f"SHOW TABLES LIKE '{table_name}'")return self.cursor.fetchone() is not Nonedef create_table(self, table_name, columns):column_str = ', '.join(columns)statement = f"CREATE TABLE {table_name} ({column_str})"self.cursor.execute(statement)self.connection.commit()def close(self):self.cursor.close()self.connection.close()

使用示例:

tool = MySQLTool(host='localhost', user='root', password='password', database='mydb')
tool.connect()table_name = 'mytable'
columns = ['id INT PRIMARY KEY AUTO_INCREMENT','name VARCHAR(100)','age INT','email VARCHAR(100)'
]if not tool.table_exists(table_name):tool.create_table(table_name, columns)print(f"Table {table_name} created successfully.")
else:print(f"Table {table_name} already exists.")tool.close()

在上面的示例中,我们首先创建了一个MySQLTool类,并在初始化方法中传入了数据库的连接信息。然后使用connect方法连接到数据库。

table_exists方法用于判断给定的数据表是否存在,它执行了一个SHOW TABLES查询,并检查返回结果是否有值。

create_table方法用于创建数据表,它接受数据表名称和列定义作为参数,然后执行一个CREATE TABLE语句创建表格。

最后,使用close方法关闭数据库连接。

在使用示例中,我们首先创建了一个MySQLTool对象并连接到数据库。然后定义了一个数据表名称和列定义列表。我们使用table_exists方法检查表格是否存在,如果不存在,则使用create_table方法创建表格。最后,使用close方法关闭数据库连接。