紧接上回,在上一篇章中我们爬取了豆瓣影评数据,在这一章中,我们就将爬取的数据存入数据库。
创建数据表
首先net start mysql启动数据库,并创建一个名为film_comments的数据库,这数据库基操就不多说了。接着,就用Python的pymsql库连接数据库并创建一张comments表。
import pymysql
# 使用 connect 方法,传入数据库地址,账号密码,数据库名就可以得到你的数据库对象
db = pymysql.connect(host='****', user='****', password='****', database='film_comments')
# 接着我们获取 cursor 来操作我们的这个数据库
cursor = db.cursor()
# 比如我们来创建一张数据表
sql = ""create table Comments (
rating char(2) not null,
comment char(100))""
cursor.execute(sql)
运行完后去数据库看看结果:
插入数据
f = open('data.txt','r',encoding='utf-8')
lines = f.readlines()
f.close()
# 这里浅浅地试几条数据
for line in lines[0:4]:
line = line.strip().split('\t')
rating = line[0]
comment = line[1]
# 插入一条记录
sql = "insert into comments(rating, comment) values ('{}', '{}')".format(rating,comment)
try:
cursor.execute(sql)
db.commit()
except:
# 回滚
db.rollback()
# 最后我们关闭这个数据库的连接
db.close()
看看结果:
忽略第一行哈,那是我一开始插入试试的一条。