实现一个MYSQL工具类,包含判断创建数据表是否存在,创建数据表,删除数据表,获取数据表元数据
时间: 2023-01-29 07:40:18 浏览: 85
首先,你需要使用Python的MySQLdb模块来连接到MySQL数据库,并获取一个数据库游标,这样才能执行SQL语句。
下面是一个简单的MySQL工具类的例子,它包含了判断数据表是否存在、创建数据表、删除数据表、获取数据表元数据四个功能:
```python
import MySQLdb
class MySQLUtil:
def __init__(self, host, port, user, password, database):
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
self.conn = MySQLdb.connect(
host=self.host,
port=self.port,
user=self.user,
password=self.password,
database=self.database,
charset='utf8'
)
self.cursor = self.conn.cursor()
def __del__(self):
self.cursor.close()
self.conn.close()
def table_exists(self, table_name):
"""判断数据表是否存在"""
sql = "SHOW TABLES;"
self.cursor.execute(sql)
tables = [self.cursor.fetchall()]
table_list = re.findall('(\'.*?\')', str(tables))
table_list = [re.sub("'", '', each) for each in table_list]
if table_name in table_list:
return True
else:
return False
def create_table(self, table_name, attr_list):
"""创建数据表"""
if not self.table_exists(table_name):
attr_str = ','.join(attr_list)
sql = "CREATE TABLE {}({});".format(table_name, attr_str)
self.cursor.execute(sql)
self.conn.commit()
def delete_table(self, table_name):
"""删除数据表"""
if self.table_exists(table_name):
sql = "DROP TABLE {};".format(table_name)
self.cursor.execute(sql)
self.conn.commit()
def get_table_metadata(self, table_name):
"""获取数据表元数据"""
if self.table_exists(table_name):
sql =
阅读全文