一、建立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("---------------------------------------------------------")