Python连接数据库
2017-09-22 11:07
169 查看
#!/usr/bin/env python # coding:utf-8 import sys # reload(sys) # sys.setdefaultencoding("utf-8") import pymysql import pymysql.cursors
用phpadmin新建在mysql中新建自己的一个数据库,douban,然后新建一个表movie,当然也可以用代码建
用Python连接数据库,然后用excute()方法想数据库中写入数据,数据库语言也就三种select updata delet
用完数据库别忘了关闭,cursor.close() db.close()
#!/usr/bin/env python # coding:utf-8 import sys # reload(sys) # sys.setdefaultencoding("utf-8") import pymysql import pymysql.cursors
db = 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 = 0
for line in fr:
try:
count += 1
# count表示当前处理到第几行了
print (count)
# 跳过表头
if count == 1:
continue
# strip()函数可以去掉字符串两端的空白符
# split()函数按照给定的分割符将字符串分割为列表
line = line.strip().split('^')
# 插入数据,注意对齐字段
# execute()函数第一个参数为要执行的SQL命令
# 这里用字符串格式化的方法生成一个模板
# %s表示一个占位符
# 第二个参数为需要格式化的参数,传入到模板中
curs
98e8
or.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()
大概流程,涉及到具体数据库更细粒度的操作,要再学习。
相关文章推荐
- python3.6 使用 pymysql 连接 Mysql 数据库及 简单的增删改查操作
- python---pymsql+flask_sqlalchemy连接数据库
- Python连接mssql数据库编码问题解决方法
- python自动化之连接数据库
- python使用mysqldb连接数据库操作方法示例详解
- 学习python之编写简单简单连接数据库并执行查询操作
- python简单连接数据库
- 数据库操作-表合并-Python连接Mysql-批量修改列属性-csv读入Python
- MySQl-python模块,python连接数据库出现的问题
- python和数据库连接(转)
- python 交互式命令行数据库连接助手 -- mysql、sql server (mssql)、redis
- Python 3.6 连接mssql数据库(pymssql 方式)
- python连接数据库出报表
- Python连接数据库
- python 连接oracle 数据库
- Python 数据库连接(sqlite, mysql, oracle, postgresql, sql server)
- python连接数据库查询
- mysql-Python数据库的连接
- python 连接cassandra数据库
- python MySQLdb mysql 数据库连接