抱歉,您的浏览器无法访问本站

本页面需要浏览器支持(启用)JavaScript


了解详情 >

本文讲解Python数据库编程。

Python DB API

在没有Python DB API之前

image-20200413220115336

在有了Python DB API之后

image-20200413220446642

Python DB API运行机制

image-20200413220526822

Python DB API访问数据库流程

image-20200413220627693

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 pymysql

# 打开数据库连接 没有密码就不填写了passwd=''
db = pymysql.connect(host="localhost",port=3306, user="root")

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

# 使用 execute() 方法执行 SQL 查询
sql="select schema_name from information_schema.schemata"

cursor.execute(sql)

# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()

print ("Databases: %s " % data)

# 关闭数据库连接
cursor.close()
db.close()
1
Databases : mysql 

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 requests
import re
import json
from requests.exceptions import RequestException
import 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("&nbsp;"," "))

return info

movie_name = get_movie_name(p1)
movie_info = get_movie_info(p2)

创建数据表

image-20200419111923618

放入数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import pymysql

# 打开数据库连接
db = pymysql.connect(host="localhost",port=3306, user="root", db='test1')

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

for mn in movie_name:
sql = "insert into movie (name) VALUES ('%s')" % (mn)
print(sql)
# 使用 execute() 方法执行 SQL 查询
cursor.execute(sql)

#使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()

print ("Databases : %s " % data)

# 关闭数据库连接
db.commit()

image-20200419111848816

评论