本文讲解Python数据库编程。
Python DB API 在没有Python DB API之前
在有了Python DB API之后
Python DB API运行机制
Python DB API访问数据库流程
Python MySQL开发环境 Python代码 + MySQL服务器 = MySQL for Python
MySQL-python模块 Mac/Linux系统下无法安装可以查看这个教程
呃。。还是没有装上。MySQLdb不支持Python3,所以我们选择PyMySQL。(使用方法还是类似的)
PyMySQL PyMySQL常用对象与方法 数据库连接对象connection
连接对象:建立Python客户端与数据库的网络连接
创建方法:pymysql.connect(参数)
pymysql.connect(参数)
参数名
类型
说明
host
字符串
MySQL服务器地址
port
数字
MySQL服务器端口号(可选,默认为3306)
user
字符串
用户名
passwd
字符串
密码
db
字符串
数据库名(可选,默认访问可以连接的数据库)
Charset
字符串
连接编码
connection对象支持的方法
方法名
说明
cursor()
使用该连接创建并返回游标
commit()
提交当前事物
rollback()
回滚当前事物
close()
关闭连接
cursor对象支持的方法
参数名
说明
execute(op[.args])
执行一个数据库查询命令(select\insert\delete)
fetchone()
取得结果集里的下一行
fetchmany(size)
获取结果集里的下几行
fetchall()
获取结果集里剩下的所有行
rowcount()
最近一次execute返回数据的行数或影响行数
close()
关闭
PyMySQL连接测试 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import pymysqldb = pymysql.connect(host="localhost" ,port=3306 , user="root" ) cursor = db.cursor() sql="select schema_name from information_schema.schemata" cursor.execute(sql) data = cursor.fetchone() print ("Databases: %s " % data) cursor.close() db.close()
Python数据库编程示例 爬取数据 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 import requestsimport reimport jsonfrom requests.exceptions import RequestExceptionimport time headers = {'User-Agent' :'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36' } def get_one_page (url ): try : res = requests.get(url, headers=headers) if res.status_code == 200 : return res.text return None except RequestException: return None def urls (): return ['https://movie.douban.com/top250?start={}&filter=' .format (str (i)) for i in range (0 ,250 ,25 )] key = [] p1 = '<span class="title">(.*?)</span>' p2 = '''导[\u4e00-\u9fa5].*''' def get_movie_name (p ): key = [] for url in urls(): key += re.findall(p1, get_one_page(url)) for k in key: if "&" in k: key.remove(k) return key def get_movie_info (p ): key = [] info = [] for url in urls(): key += re.findall(p, get_one_page(url)) for i in key: info += str (i[:-7 ].replace(" " ," " )) return info movie_name = get_movie_name(p1) movie_info = get_movie_info(p2)
创建数据表
放入数据库 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 import pymysqldb = pymysql.connect(host="localhost" ,port=3306 , user="root" , db='test1' ) cursor = db.cursor() for mn in movie_name: sql = "insert into movie (name) VALUES ('%s')" % (mn) print(sql) cursor.execute(sql) data = cursor.fetchone() print ("Databases : %s " % data) db.commit()