处理数据(一)

下面是一个文档整理的例子,。
我借用了宏伦学长爬取的数据,一个豆瓣抓出来的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()
以上差不多就是对于数据库最基本的操作了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值