下面是一个文档整理的例子,。
我借用了宏伦学长爬取的数据,一个豆瓣抓出来的txt文本。
废话少说,一边讲代码一边介绍:
import MySQLdb
import MySQLdb.cursors
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
上面的代码导入了数据库和设置了编码类型为utf-8,如果没安装的自行安装,这里推荐安装MAMP(osx);WAMP(win)。
db = MySQLdb.connect(host='127.0.0.1', user='root', passwd='root', db='douban', port=8889, charset='utf8', cursorclass = MySQLdb.cursors.DictCursor)
db.autocommit(True)
cursor = db.cursor()
这里的db
导入了我们的数据库地址,可以看到有很多属性。
db.autocommit
是数据库的自动提交事务的属性,这样做就把事务更改交给系统了,爬虫适用,但是缺点是出错无法回滚(这个是个人的理解有错希望指出!)。
db.cursor
其实就是用来获得python执行Mysql命令的方法,也就是
我们所说的 操作游标。
fr = open('/Users/noah/PycharmProjects/mysql/douban_movie_clean.txt', 'r')
# #Create
# count=0
# for line in fr:
# count += 1
# print count
# if count ==1:
# continue
# line = line.strip().split('^')
# cursor.execute("insert into movie(title,url,rate,length,description) values (%s, %s, %s, %s, %s)", [line[1],line[2],line[4],line[-3],line[-1]])
# fr.close()
# #Update
# cursor.execute("update movie set title = %s, length = %s where id = 1" , [ 'Noah' ,999])
# #Read
# cursor.execute("select * from movie")
# cursor.execute("select url from movie")
# cursor.execute("select title from movie where id = 777")
# movies = cursor.fetchall()
# # movies = cursor.fetchone()
# print len(movies)
# print movies[0]
# print '\u9b42\u65ad\u84dd\u6865'.decode('unicode-escape')
# #Delete
# # cursor.execute("delete from movie where id = 1 ")
# cursor.execute("delete from movie where id = %s ",[1])
cursor.close()
db.close()
上面演示了对于数据库的听、说、读、写。
哦不对,是创建、修改、读取、删除。
但首先需要fr = open('文件路径', 'r')
open一个数据,
完事后要cursor.close()
最后要db.close()
以上差不多就是对于数据库最基本的操作了。