实现一个MYSQL工具类,包含判断创建数据表是否存在,创建数据表,删除数据表,可以获取数据表数据量,查询某一条数据,分页查询数据
时间: 2023-01-29 10:49:59 浏览: 94
查询与维护学生信息管理数据表5共37页.pdf.zip
下面是一个简单的 MySQL 工具类的示例:
```
import mysql.connector
class MySQLUtil:
def __init__(self, host, user, password, database):
self.host = host
self.user = user
self.password = password
self.database = database
def connect(self):
self.conn = mysql.connector.connect(
host=self.host,
user=self.user,
password=self.password,
database=self.database
)
self.cursor = self.conn.cursor()
def close(self):
self.cursor.close()
self.conn.close()
def table_exists(self, table_name):
"""判断数据表是否存在"""
sql = "SHOW TABLES LIKE %s"
self.cursor.execute(sql, (table_name,))
return self.cursor.fetchone() is not None
def create_table(self, table_name, columns):
"""创建数据表"""
column_str = ", ".join(f"{name} {datatype}" for name, datatype in columns.items())
sql = f"CREATE TABLE {table_name} ({column_str})"
self.cursor.execute(sql)
def delete_table(self, table_name):
"""删除数据表"""
sql = f"DROP TABLE {table_name}"
self.cursor.execute(sql)
def get_table_size(self, table_name):
"""获取数据表数据量"""
sql = f"SELECT COUNT(*) FROM {table_name}"
self.cursor.execute(sql)
return self.cursor.fetchone()[0]
def get_row(self, table_name, row_id):
"""查询某一条数据"""
sql = f"SELECT * FROM {table_name} WHERE id = %s"
self.cursor.execute(sql, (row_id,))
return self.cursor.fetchone()
def paginate(self, table_name, page, page_size):
"""分页查询数据"""
sql = f"SELECT * FROM {table_name} LIMIT %s, %s"
self.cursor.execute(sql, ((page - 1) * page_size, page_size))
return self.cursor.fetchall()
```
使用示例:
```
util = MySQLUtil("localhost", "root", "123456", "test")
util.connect()
# 判断数据表是否存在
print(util.table_exists("users"))
# 创
阅读全文