MySQLdb
安装:pip install mysql-python
import MySQLdb
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.close()
SQL教程:http://www.runoob.com/sql/sql-tutorial.html
import sys
reload(sys)
sys.setdefaultencoding("utf8")
import MySQLdb
import MySQLdb.cursors
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()
fr = open('douban_movie_clean.txt', 'r')
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()
cursor.execute("update movie set title=%s, length=%s where id=%s", ['全栈数据工程师养成攻略', 999, 1])
cursor.execute("select * from movie")
movies = cursor.fetchall()
print type(movies), len(movies), movies[0]
cursor.execute("select id, title, url from movie")
movie = cursor.fetchone()
print type(movie), len(movie), movie
cursor.execute("select id, title, url from movie order by id desc")
movie = cursor.fetchone()
print type(movie), len(movie), movie
cursor.execute("delete from movie where id=%s", [1])
cursor.close()
db.close()