Python连接数据库

来源:互联网 发布:关键词seo 编辑:程序博客网 时间:2024/06/01 09:13
#!/usr/bin/env python# coding:utf-8import sys# reload(sys)# sys.setdefaultencoding("utf-8")import pymysqlimport pymysql.cursors
  • 用phpadmin新建在mysql中新建自己的一个数据库,douban,然后新建一个表movie,当然也可以用代码建
  • 用Python连接数据库,然后用excute()方法想数据库中写入数据,数据库语言也就三种select updata delet
  • 用完数据库别忘了关闭,cursor.close() db.close()
#!/usr/bin/env python# coding:utf-8import sys# reload(sys)# sys.setdefaultencoding("utf-8")import pymysqlimport pymysql.cursorsdb = pymysql.Connect(host='127.0.0.1', user='root', passwd='', db='douban', port=3306, charset='utf8')db.commit(True)cursor = db.cursor()# Create# 读取数据fr = open('../data/douban_movie_clean.txt', 'r',encoding="utf-8")print("----")count = 0for line in fr:    try:        count += 1    # count表示当前处理到第几行了        print (count)        # 跳过表头        if count == 1:            continue        # strip()函数可以去掉字符串两端的空白符        # split()函数按照给定的分割符将字符串分割为列表        line = line.strip().split('^')        # 插入数据,注意对齐字段        # execute()函数第一个参数为要执行的SQL命令        # 这里用字符串格式化的方法生成一个模板        # %s表示一个占位符        # 第二个参数为需要格式化的参数,传入到模板中        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]])    except Exception as e:        print("error")# 关闭读文件fr.close()# Update# 更新需要提供条件、需要更新的字段、更新的新值# 以下对于id为1的记录,将其title和length两个字段进行更新cursor.execute("update movie set title=%s, length=%s where id=%s", ['全栈数据工程师养成攻略', 999, 1])# Read# 读取全部数据的全部字段cursor.execute("select * from movie")movies = cursor.fetchall()# 返回元组,每一项都是一个字典# 对应一条记录的全部字段和字段值print (type(movies), len(movies), movies[0])# 读取一条数据的部分字段# 返回一个字段,对应所选择的部分字段和字段值cursor.execute("select id, title, url from movie where id=2")movie = cursor.fetchone()print (type(movie), len(movie), movie)# # 读取一条数据的部分字段# # 按id降序排序,默认为升序cursor.execute("select id, title, url from movie order by id desc")movie = cursor.fetchone()print (type(movie), len(movie), movie)# # Delete# # 删除数据务必要提供删除条件# # 此处删除id为1的记录cursor.execute("delete from movie where id=%s", [1])# 关闭数据库连接cursor.close()db.close()

大概流程,涉及到具体数据库更细粒度的操作,要再学习。

原创粉丝点击