我用python封装了个实现对MySQL建库、建表并实现增删改查操作的类
初级版:
class MySQLUtil:
def __init__(self):
self.conn = pymysql.Connection(
host="localhost", # 主机名 IP地址
user="root", # 账户
password="888888", # 密码
port=3306, # 端口
)
p2 = MySQLUtil()
conn = p2.conn
# 选择
conn.select_db("testdb")
# 获取游标
cursor = conn.cursor()
# 变量
update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
table_name = 'test_table_update_time'
# sql语句
drop_sql= f"drop table if exists {table_name}"
create_sql = 'id bigint(20) primary key auto_increment,name varchar(20),age int,sex varchar(10), update_time varchar(50)'
create_table = f"Create Table {table_name}({create_sql})"
insert_sql = f"insert into {table_name}(name,age,sex,update_time)values('高启强',48,'男','{update_time}')"
query_sql = "select * from test_table_update_time"
# 执行建表语句
cursor.execute(drop_sql)
time.sleep(1)
cursor.execute(create_table) # 不需要commit
time.sleep(1)
cursor.execute(insert_sql)
time.sleep(1)
cursor.execute(query_sql)
time.sleep(1)
# 提交事务
conn.commit()
# 关闭游标
cursor.close()
# 关闭数据库连接
conn.close()
中高级版:
import pymysql
import time
class MySQLUtil:
def __init__(self):
self.conn = pymysql.Connection(
host="localhost", # 主机名 IP地址
user="root", # 账户
password="xxxxx", # 密码
port=3306, # 端口
# autocommit=True
)
def run(self):
# 选择
self.conn.select_db("testdb")
# 获取游标
cursor = self.conn.cursor()
# 变量
update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
table_name = 'test_table_update_time'
# sql语句
drop_sql= f"drop table if exists {table_name}"
create_sql = 'id bigint(20) primary key auto_increment,name varchar(20),age int,sex varchar(10), update_time datetime'
create_table = f"Create Table {table_name}({create_sql})"
insert_sql = f"insert into {table_name}(name,age,sex,update_time)values('高启强',48,'男','{update_time}')"
query_sql = "select * from test_table_update_time"
# 执行建表语句
cursor.execute(drop_sql)
time.sleep(0.1)
cursor.execute(create_table) # 不需要commit
time.sleep(0.1)
cursor.execute(insert_sql)
time.sleep(0.1)
cursor.execute(query_sql)
time.sleep(0.1)
# 提交事务
self.conn.commit()
# 通过游标获取执行结果
result = cursor.fetchall()
# 关闭游标
cursor.close()
# 关闭数据库连接
self.conn.close()
if __name__ == '__main__':
MySQLUtil = MySQLUtil()
MySQLUtil.run()