一、创建mysql工具类py文件
import pymysql
class MysqlUtil:
def __init__(self, host, port, user, password, database):
"""
初始化MysqlUtil类实例。
Args:
host (str): MySQL主机名或IP地址。
port (int): MySQL端口号。
user (str): MySQL用户名。
password (str): MySQL密码。
database (str): 要连接的数据库名称。
"""
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
self.conn = None
self.cursor = None
self.batch_size = 1000
def init_connect(self):
"""
初始化与MySQL数据库的连接。
"""
try:
self.conn = pymysql.connect(
host=self.host,
port=self.port,
user=self.user,
password=self.password,
database=self.database
)
self.cursor = self.conn.cursor()
except pymysql.Error as e:
print(f"连接mysql数据库错误: {str(e)}")
def close_connection(self):
"""
关闭与MySQL数据库的连接。
"""
try:
if self.conn:
self.conn.close()
except pymysql.Error as e:
print(f"关闭连接mysql数据库错误: {str(e)}")
def close_cursor(self):
"""
关闭游标。
"""
try:
if self.cursor:
self.cursor.close()
except pymysql.Error as e:
print(f"关闭游标错误: {e}")
def create_table(self, table_name, table_fields, extend=''):
"""
创建新的数据库表。
Args:
table_name (str): 表名。
table_fields (list): 包含字段名和字段类型的列表,例如[('id', 'INT'), ('name', 'VARCHAR(255)')].
extend (str): 可选的额外信息,如表引擎类型等。
"""
try:
self.init_connect()
temp_field = []
for field in table_fields:
temp_field.append(f"{field[0]} {field[1]}")
field_info = ", ".join(temp_field)
create_table_sql = f'CREATE TABLE `{table_name}` ({field_info}) {extend}'
self.cursor.execute(create_table_sql)
self.conn.commit()
except pymysql.Error as e:
self.conn.rollback()
print(f"建表错误: {str(e)}")
finally:
self.close_cursor()
self.close_connection()
def drop_table(self, table_name):
"""
删除数据库表。
Args:
table_name (str): 要删除的表名。
"""
try:
self.init_connect()
create_table_sql = f'DROP TABLE `{table_name}`'
self.cursor.execute(create_table_sql)
self.conn.commit()
except pymysql.Error as e:
self.conn.rollback()
print(f"删表错误: {str(e)}")
finally:
self.close_cursor()
self.close_connection()
def insert_data(self, table_name, table_fields, table_data):
"""
向数据库表中插入数据。
Args:
table_name (str): 表名。
table_fields (list): 包含字段名和字段类型的列表,例如[('id', 'INT'), ('name', 'VARCHAR(255)')].
table_data (list): 包含要插入的数据的列表,例如[(0, '张三1'), (0, '张三2')].
"""
try:
self.init_connect()
temp_field = []
for field in table_fields:
temp_field.append(f"{field[0]}")
field_info = ", ".join(temp_field)
data_info = ''
for data in table_data:
data_info += str(data) + ','
insert_data_sql = f'INSERT INTO {table_name}({field_info}) VALUES{data_info[:-1]}'
self.cursor.execute(insert_data_sql)
self.conn.commit()
except pymysql.Error as e:
self.conn.rollback()
print(f"插入数据错误: {str(e)}")
finally:
self.close_cursor()
self.close_connection()
def insert_data_v2(self, table_name, table_fields, table_data):
"""
向数据库表中插入数据_v2。
Args:
table_name (str): 表名。
table_fields (list): 包含字段名和字段类型的列表,例如[('id', 'INT'), ('name', 'VARCHAR(255)')].
table_data (list): 包含要插入的数据的列表,例如[(0, '张三1'), (0, '张三2')].
"""
try:
self.init_connect()
temp_field = []
for field in table_fields:
temp_field.append(field[0])
field_info = ", ".join(temp_field)
placeholders = ', '.join(['%s'] * len(table_fields))
insert_data_sql = f'INSERT INTO {table_name}({field_info}) VALUES ({placeholders})'
batch_data = []
for data in table_data:
batch_data.append(data)
if len(batch_data) >= self.batch_size:
self.cursor.executemany(insert_data_sql, batch_data)
self.conn.commit()
batch_data = []
if batch_data:
self.cursor.executemany(insert_data_sql, batch_data)
self.conn.commit()
except pymysql.Error as e:
self.conn.rollback()
print(f"插入数据错误: {str(e)}")
finally:
self.close_cursor()
self.close_connection()
def delete_data(self, table_name, extend=''):
"""
从数据库表中删除数据。
Args:
table_name (str): 表名。
extend (str): 可选的额外条件,用于指定要删除的数据。
"""
try:
self.init_connect()
delete_data_sql = f'DELETE FROM {table_name} {extend}'
self.cursor.execute(delete_data_sql)
self.conn.commit()
except pymysql.Error as e:
self.conn.rollback()
print(f"删除数据错误: {str(e)}")
finally:
self.close_cursor()
self.close_connection()
def select_data(self, table_name, select_fields='*', extend=''):
"""
从数据库表中查询数据。
Args:
table_name (str): 表名。
select_fields (str): 查询的字段(默认为*)
extend (str): 可选的扩展条件,用于指定要查询的数据。
Returns:
list: 包含查询结果的元组列表。
"""
try:
self.init_connect()
delete_data_sql = f'SELECT {select_fields} FROM {table_name} {extend}'
self.cursor.execute(delete_data_sql)
self.conn.commit()
result = self.cursor.fetchall()
return result
except pymysql.Error as e:
self.conn.rollback()
print(f"查询数据错误: {str(e)}")
finally:
self.close_cursor()
self.close_connection()
二、创建执行脚本py文件
import time
from mysql_util import MysqlUtil
from faker import Faker
if __name__ == '__main__':
msql = MysqlUtil('192.168.0.106', 3306, 'root', '123456', 'test01')
faker = Faker('zh_CN')
for i in range(1, 11):
table_name = f'user_info{i}'
table_fields = [
('id', 'bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY'),
('name', 'varchar(100) DEFAULT NULL'),
('age', 'int(11) DEFAULT NULL')
]
start_timestamp = time.time()
msql.create_table(table_name, table_fields)
table_data = []
for _ in range(1000):
name = faker.name()
age = faker.random_int(min=0, max=120)
temp_data = (0, name, age)
table_data.append(temp_data)
msql.insert_data_v2(table_name, table_fields, table_data)
end_timestamp = time.time()
print(f"测试数据表创建成功,单次耗时 {(end_timestamp - start_timestamp):.2f} 秒")
print("---------------------------------------------------------")
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY