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()
大概流程,涉及到具体数据库更细粒度的操作,要再学习。
阅读全文
0 0
- python连接mysql数据库
- python连接mysql数据库
- python连接MySQL数据库
- Python连接mysql数据库
- python--连接数据库篇
- python连接mysql数据库
- Python连接mysql数据库
- Python连接mysql数据库
- Python连接MySql数据库
- Python数据库的连接
- Python 连接mysql数据库
- Python连接数据库-pyodbc
- Python连接数据库
- Python 连接数据库
- python连接mysql数据库
- Python数据库的连接
- Python连接mysql数据库
- Python连接mysql数据库
- 有用的Java程序片段
- 常用手机尺寸以及分辨率
- LinuxStudyNote(8)-Linux常用命令(2)-文件处理命令(3)-切换工作目录命令cd
- AndroidStudio通用混淆配置文件
- 钓鱼网站:网络诈骗主要的劫财暗道
- Python连接数据库
- 实际项目中遇到的一些小问题
- 直方图变换
- 双系统音量的问题
- AngularJs购物车实现
- 几种常见的排序算法分析学习
- mnist_tf
- Flash Player和Adobe AIR垃圾收集内幕
- 30分钟掌握ES6/ES2015核心内容(上)