作业1-5

6月23

1.请简述安装pymysql的流程:

①可以在pycharm页面选择setting进行下载安装;
②可以在终端用命令进行安装:pip install pymysql

2.请简述事务的四个特性

原子性、一致性、隔离性、持久性

3.请用pymysql完成以下需求:

①插入一本书,名字为‘python从入门到放弃’,阅读量为50,评论零为0,发布日期是2020-01-01;
②测试工程是发现评论数不对,要求修改为250;
③老板觉得名字不吉利,要求下架;
④删除后确定是否删除;
import pymysql

class DBUtil():

conn = None
cursor = None

@classmethod
def get_conn(self):
if self.conn is None:
self.conn = pymysql.connect(host=’192.168.0.171’,
port=3306,
user=’root’,
password=’root’,
datebase=’root’)
return self.conn

@classmethod
def get_cursor(self):
if self.cursor is None:
self.cursor = self.get_conn().cursor()
return self.cursor

@classmethod
def exe_sql(self,sql):
try:
cursor = self.get_cursor()
cursor.execute(sql)
if sql.split()[0].lower() = “select”:
return cursor.fetchall()
else:
self.conn.commit()
return cursor.fetchall()

except Exception as e:
self.conn.rollback()
print(e)

finally:
self.cursor_close()
self.conn_close()

@classmethod
def cursor_close(self):
if self.cursor:
self.cursor.close()
self.cursor = None

@classmethod(self):
if self.conn:
self.conn.close()
Self.conn = None

①import DBUtil

sql = “insert into t_book(title, read, comment, pub_date) values(python从入门到放弃, 50, 0, 2020-01-01);”
result = DBUtil.exx_sql(sql)
print(result)

②sql = “update t_book set commet = 250 where title= python从入门到放弃; ”
result = DBUtil.exe_sql(sql)
print(result)

③sql = “delete from t_book where title= python从入门到放弃; ”
④result = DBUtil.exe_sql(sql)
print(result)

4.小明正在练习pymysql,他写入了插入数据库的代码,在代码中能查到,但是查询数据库时,却查不到他插入的数据,请帮他找一找原因,并写出改正代码。

import pymysql 
# 建立连接 
conn = pymysql.connect("localhost",'root','root','books') 
# 获取游标 
cursor = conn.cursor() 
sql_insert = "insert into t_book(title,`read`,`comment`,pub_date) values('小明的 
哥哥叫大明',50,0,'2020-01-01');" 
cursor.execute(sql_insert) 
cursor.execute("select * from t_book where title='小明的哥哥叫大明';") 
print("小明插入的书:", cursor.fetchall()) 
# 关闭游标 
cursor.close() 
# 关闭连接 
conn.close() 
# 输出 
小明插入的书: ((8, '小明的哥哥叫大明', datetime.date(2020, 1, 1), 50, 0, 0),) 
# 通过数据库连接查询结果: 
1 射雕英雄传 1980-05-01 12 34 0 
2 天龙八部 1986-07-24 36 40 0 
3 笑傲江湖 1995-12-24 20 80 0

答:因为没有提交事务。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容