研一寒假MySQL数据库学习笔记(五)
本节是记录数据库学习笔记的最后一篇,记录几个简单的数据库使用案例。
1. 数据库写操作
''
数据库写操作示例
对数据库写操作会默认开启事务,
如果数据表支持事务需要commit提交才能生效,
如果数据表不支持事务,则execute执行语句后立即生效
'''
import pymysql
# 参数字典
kwargs={
"host":"localhost",
"port":3306,
"user":"root",
"password":"123456",
"database":"stu",
"charset":"utf8"
}
# 连接数据库
db=pymysql.connect(**kwargs)# 解包
# 生成游标:执行sql操作数据,得到操作结果的对象
cur=db.cursor()
# 数据写操作
# sql="update hobby set price=8848 where id=1;"
score=99
id=3
try:
# sql="update class set score=1000 where id=1;"
# cur.execute(sql)
# sql = "update class set score=999 where id=2;"
# cur.execute(sql)
# sql="update class set score=%s where id=%s;"
# cur.execute(sql,[score,id])
# sql = "update class set score=%s where name=%s;"
# cur.execute(sql, [score, "大美女"])
data=[("张junjun",27,'m',95),("en博",23,'m',95),
("飞飞",47,'m',92)]
sql="insert into class (name,age,sex,score) values" \
"(%s,%s,%s,%s);"
cur.executemany(sql,data)
except Exception as e:
print(e)
db.rollback() # 事务回滚
else:
db.commit() #提交事务
# 关闭
cur.close()
db.close()
2. 数据库读操作
'''
数据库的读取操作
'''
import pymysql
# 参数字典
kwargs={
"host":"localhost",
"port":3306,
"user":"root",
"password":"123456",
"database":"stu",
"charset":"utf8"
}
# 连接数据库
db=pymysql.connect(**kwargs)# 解包
# 生成游标:执行sql操作数据,得到操作结果的对象
cur=db.cursor()
# 数据读取操作
sql="select name,score from class where score>%s;"
cur.execute(sql,[85])
# 获取查询1条结果
one=cur.fetchone()
print(one)
# 获取3条查询结果
many=cur.fetchmany(3)
print(many)
# 获取所有查询结果
all=cur.fetchall()
print(all)
# 关闭
cur.close()
db.close()
3. 数据库上传与保存图片
import pymysql
# 参数字典
kwargs={
"host":"localhost",
"port":3306,
"user":"root",
"password":"123456",
"database":"stu",
"charset":"utf8"
}
# 连接数据库
db=pymysql.connect(**kwargs)# 解包
# 生成游标:执行sql操作数据,得到操作结果的对象
cur=db.cursor()
# 存入图片
with open("01.jpeg","rb") as fr:
data=fr.read()
sql="update class set image=%s where id=1;"
cur.execute(sql,[data])
db.commit()
# 取出图片
sql="select name,image from class where id=1;"
cur.execute(sql)
name,image=cur.fetchone()
with open(name+'.jpeg','wb') as fw:
fw.write(image)
# 关闭
cur.close()
db.close()
4. 一个小练习–查单词
'''
练习01:使用dict.txt文件完成
创建一个数据库 dict 使用utf8格式
在该数据库下创建一个数据表words
id word mean
将单词本中的单词插入该数据表
'''
import pymysql
import re
class Dict():
def __init__(self):
# 参数字典
self.kwargs = {
"host": "localhost",
"port": 3306,
"user": "root",
"password": "123456",
"database": "dict",
"charset": "utf8"
}
# 连接数据库
self.db = pymysql.connect(**self.kwargs) # 解包
# 生成游标:执行sql操作数据,得到操作结果的对象
self.cur = self.db.cursor()
def get_word(self):
data=[]
fr = open("dict.txt")
for line in fr:
word, mean = line.split(" ", 1)
data.append((word, mean.strip()))
# 方法二
for line in fr:
# [(word,mean)]
data += re.findall("(\w+)\s+(.+)", line)
# 数据写操作
# sql="update hobby set price=8848 where id=1;"
with open("dict.txt", "r") as f:
data = f.readlines()
print(len(data))
word_list = []
mean_list = []
for i in range(len(data)):
word = data[i].split(' ')[0]
temp = data[i].split(' ')[1:]
mean = " ".join(temp).strip()
mean_list.append(mean)
word_list.append(word)
print('word_list:', len(word_list))
print('mean_list:', len(mean_list))
print(word_list[:10])
def insert_word(self):
try:
data_list=[]
for i in range(10000):
word=word_list[i]
mean=mean_list[i]
temp=(word,mean)
data_list.append(temp)
sql="insert into words (word,mean) values" \
"(%s,%s);"
cur.executemany(sql,data_list)
except Exception as e:
print(e)
db.rollback() # 食物回滚
else:
db.commit() #提交事务
# 关闭
cur.close()
db.close()
在这个案例中,insert_word方法有一点点错误,word_list需要作为参数或者写成全局变量吧?不然不能直接在该方法中使用。
数据库的学习暂时告一段落了,下一节记录网络并发编程的内容。