# coding=utf-8
import pymysql
class P_Mysql:
def __init__(self):
# 1.连接数据库-----------------------------------------------------------------------
self.conn = pymysql.connect(
host = "localhost",
port = 3316,
user = "root",
password = "",
db = "stuinfo",
charset = "utf8",
autocommit = False, # 是否自动提交
)
with self.conn:
# 2. 创建游标对象-----------------------------------------------------------------------
self.cur = self.conn.cursor( )
# 设置游标类型,默认游标类型为元组形式
# 将游标类型设置为字典形式
# conn = conn.cursor(cursor = pymysql.cursors.DictCursor)
des = self.cur.description
print("表的描述:", des)
# 3.创建数据表-----------------------------------------------------------------------
def create_table(self):
try:
create_table = "create table hello (id int,name varchar(30));"
self.cur.execute(create_table)
except Exception as e:
print(f"创建数据表失败:{e}")
# 如果发生错误则回滚
self.conn.rollback( )
else:
print("创建数据表成功")
self.cur.close( ) # 关闭游标
self.conn.close( ) # 关闭连接
# 4. 对于数据库进行增删改查-----------------------------------------------------------------------
def insert_data(self):
try:
# 插入一条数据*****************************************
# insert_data = "insert into hello values(2,'fensi');"
# 插入多条数据*****************************************
info = [(i, 'westos-%s' % (i,)) for i in range(3, 101)]
insert_data = "insert into hello values('%s','%s');"
print(f"影响的行数:{self.cur.rowcoun}")
self.cur.executemany(insert_data, info) # 如果量比较大,换别的方式
except Exception as e:
print(f"插入数据失败:{e}")
# 如果发生错误则回滚
self.conn.rollback( )
else:
self.conn.commit( )
print("插入数据成功")
self.cur.close( ) # 关闭游标
self.conn.close( ) # 关闭连接
def select_data(self):
try:
select_data = "select * from hello;"
result = self.cur.execute(select_data)
print(f"数据的数量:{result}")
print(self.cur.fetchone( )) # 获取下一个查询结果集
print(self.cur.fetchmany(4)) # 获取制定个数个查询结果集
print(self.cur.fetchall( )) # 获取所有的查询结果
except Exception as e:
print(f"没找到数据:{e}")
# 如果发生错误则回滚
self.conn.rollback( )
if __name__ == '__main__':
mysql = P_Mysql( )
mysql.select_data( )
Python pymysql基础认识
最新推荐文章于 2023-03-21 07:45:00 发布