### 1.安裝
[安裝地址](/1.kaifahuanjing/15-cun-chu-ku-de-an-zhuang/151-pymysqlde-an-zhuang.md)
### 2.連接數據庫
在連接數據庫之前,確保mysql已經打開了
```
import pymysql
# pymysql使用connect()方法連接數據庫
db = pymysql.connect(host='127.0.0.1',user='root',password='123456',port=3306)
# 獲取mysql的操作游標
cursor = db.cursor()
# 使用execute()方法執行sql語句
cursor.execute('select version()')
# 使用fetchone()方法來獲得第一條數據
# fetchall()獲取全部數據
data = cursor.fetchone()
print("database version:",data)
# 創建數據庫并設置默認編碼為utf-8
cursor.execute("create database spiders DEFAULT CHARACTER set utf8")
db.close()
```
### 3.創建表結構
| 字段名 | 含義 | 類型 |
| :--- | :--- | :--- |
| name | 名字 | varchar |
| age | 年齡 | int |
```
import pymysql
db = pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='spiders')
cursor = db.cursor()
# 判斷在數據庫是否存在students表并創建name和age兩個字段
# create table if not exists students(name varchar(255) not null,age int not null,primary key(name))
sql = 'create table if not exists students (name VARCHAR(255) not null,age int NOT NULL,PRIMARY KEY (NAME ))'
cursor.execute(sql)
db.close()
```
### 4.插入數據
```
mysql插入語句:insert into students(name,age) values('miku',18);
```
```
import pymysql
# 定義數據
name = 'miku'
age = 18
db = pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='spiders')
cursor = db.cursor()
sql = 'insert into students(name,age) VALUES (%s,%s)'
try:
cursor.execute(sql,(name,age))
# 提交
db.commit()
except:
# 回滾
db.rollback()
db.close()
```
根據字典動態構造sql語句
```
import pymysql
data = {
'name':'angle',
'age':18,
}
db = pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='spiders')
cursor = db.cursor()
table = "students"
keys = ','.join(data.keys())
values = ','.join(["%s"] * len(data))
sql = "insert into {table}({keys}) VALUES ({values})".format(table=table,keys=keys,values=values)
try:
if cursor.execute(sql,tuple(data.values())):
print("成功")
db.commit()
except:
print("失敗")
db.rollback()
db.close()
```
### 5.更新數據
更新name字段值為angle的age字段,更改為235
```
import pymysql
db = pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='spiders')
cursor = db.cursor()
sql = "update students set age = %s where name = %s"
try:
cursor.execute(sql,('235','angle'))
db.commit()
except:
db.rollback()
db.close()
```
根據字典動態構造sql更新語句
```
import pymysql
data = {
"name":"angle",
"age":18,
}
table = "students"
keys = ','.join(data.keys())
values = ','.join(["%s"]*len(data))
db = pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='spiders')
cursor = db.cursor()
# insert into students(name,age) VALUES (%s,%s) ON DUPLICATE KEY UPDATE name = %s, age = %s
# ON DUPLICATE KEY UPDATE:如果主鍵存在就執行更新操作
sql = "insert into {table}({keys}) VALUES ({values}) ON DUPLICATE KEY UPDATE".format(table=table,keys=keys,values=values)
update = ",".join([" {key} = %s".format(key=key) for key in data])
sql += update
print(sql)
try:
if cursor.execute(sql,tuple(data.values())*2):
print("成功")
db.commit()
except:
print("失敗")
db.rollback()
db.close()
```
### 6.刪除數據
```
mysql語句:delete from table where 條件
```
```
import pymysql
db = pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='spiders')
cursor = db.cursor()
table = "students"
condition = "age = 18"
sql = "delete from {table} where {condition}".format(table=table,condition=condition)
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
```
### 7.查詢數據
```
手動添加兩條數據
mysql> insert into students values("angle",18);
Query OK, 1 row affected (0.06 sec)
mysql> insert into students values("miku",18);
Query OK, 1 row affected (0.09 sec)
```
```
import pymysql
db = pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='spiders')
cursor = db.cursor()
table = "students"
condition = "age = 18"
sql = "select * from students where age = 18"
try:
cursor.execute(sql)
# 獲取數據的數目
print("count:",cursor.rowcount)
# fetchone()方法獲取第一條數據
one = cursor.fetchone()
print("one data:",one)
# 調用fecthall()方法獲取所有數據
results = cursor.fetchall()
print("results:",results)
print("results type:",type(results))
for row in results:
print(row)
db.commit()
except:
print("error")
# db.rollback()
db.close()
```
可以使用fetchone\(\)循環獲取所有數據,注意fetchone\(\)方法,獲取一條數據后,當前的第一條數據被取出來了就沒有了,數據的指針會指向下一條數據
- 介紹
- 1.開發環境配置
- 1.1 python3的安裝
- 1.1.1 windows下的安裝
- 1.1.2 Linux下的安裝
- 1.1.3 Mac下的安裝
- 1.2 請求庫的安裝
- 1.2.1 requests的安裝
- 1.2.2 selenium的安裝
- 1.2.3 ChromeDriver的安裝
- 1.2.4 GeckoDriver 的安裝
- 1.2.5 PhantomJS的安裝
- 1.2.6 aiohttp的安裝
- 1.3 解析庫的安裝
- 1.3.1 lxml的安裝
- 1.3.2 Beautiful Soup的安裝
- 1.3.3 pyquery的安裝
- 1.3.4 tesserocr的安裝
- 1.4 數據庫的安裝
- 1.4.1 MySQL的安裝
- 1.4.2 MongoDB的安裝
- 1.4.3 Redis的安裝
- 1.5 存儲庫的安裝
- 1.5.1 PyMySQL的安裝
- 1.5.2 PyMongo的安裝
- 1.5.3 redis-py的安裝
- 1.5.4 RedisDump的安裝
- 1.6 Web庫的安裝
- 1.6.1 Flask的安裝
- 1.6.2 Tornado的安裝
- 1.7 App爬取相關庫的安裝
- 1.7.1 Charles的安裝
- 1.7.2 mitmproxy的安裝
- 1.7.3 Appium的安裝
- 1.8 爬蟲框架的安裝
- 1.8.1 pyspider的安裝
- 1.8.2 Scrapy的安裝
- 1.8.3 Scrapy-Splash的安裝
- 1.8.4 ScrapyRedis的安裝
- 1.9 布署相關庫的安裝
- 1.9.1 Docker的安裝
- 1.9.2 Scrapyd的安裝
- 1.9.3 ScrapydClient的安裝
- 1.9.4 ScrapydAPI的安裝
- 1.9.5 Scrapyrt的安裝
- 1.9.6-Gerapy的安裝
- 2.爬蟲基礎
- 2.1 HTTP 基本原理
- 2.1.1 URI和URL
- 2.1.2 超文本
- 2.1.3 HTTP和HTTPS
- 2.1.4 HTTP請求過程
- 2.1.5 請求
- 2.1.6 響應
- 2.2 網頁基礎
- 2.2.1網頁的組成
- 2.2.2 網頁的結構
- 2.2.3 節點樹及節點間的關系
- 2.2.4 選擇器
- 2.3 爬蟲的基本原理
- 2.3.1 爬蟲概述
- 2.3.2 能抓怎樣的數據
- 2.3.3 javascript渲染的頁面
- 2.4 會話和Cookies
- 2.4.1 靜態網頁和動態網頁
- 2.4.2 無狀態HTTP
- 2.4.3 常見誤區
- 2.5 代理的基本原理
- 2.5.1 基本原理
- 2.5.2 代理的作用
- 2.5.3 爬蟲代理
- 2.5.4 代理分類
- 2.5.5 常見代理設置
- 3.基本庫使用
- 3.1 使用urllib
- 3.1.1 發送請求
- 3.1.2 處理異常
- 3.1.3 解析鏈接
- 3.1.4 分析Robots協議
- 3.2 使用requests
- 3.2.1 基本用法
- 3.2.2 高級用法
- 3.3 正則表達式
- 3.4 抓取貓眼電影排行
- 4.解析庫的使用
- 4.1 使用xpath
- 4.2 使用Beautiful Soup
- 4.3 使用pyquery
- 5.數據存儲
- 5.1 文件存儲
- 5.1.1 TXT 文件存儲
- 5.1.2 JSON文件存儲
- 5.1.3 CSV文件存儲
- 5.2 關系型數據庫存儲
- 5.2.1 MySQL的存儲
- 5.3 非關系數據庫存儲
- 5.3.1 MongoDB存儲
- 5.3.2 Redis存儲
- 6.Ajax數據爬取
- 6.1 什么是Ajax
- 6.2 Ajax分析方法
- 6.3 Ajax結果提取
- 6.4 分析Ajax爬取今日頭條街拍美圖
- 7.動態渲染頁面爬取
- 7.1 Selenium的使用
- 7.2 Splash的使用
- 7.3 Splash負載均衡配置
- 7.4 使用selenium爬取淘寶商品
- 8.驗證碼的識別
- 8.1 圖形驗證碼的識別
- 8.2 極驗滑動驗證碼的識別
- 8.3 點觸驗證碼的識別
- 8.4微博宮格驗證碼的識別
- 9.代理的使用
- 9.1 代理的設置
- 9.2 代理池的維護
- 9.3 付費代理的使用
- 9.4 ADSL撥號代理
- 9.5 使用代理爬取微信公總號文章
- 10.模擬登錄
- 10.1 模擬登陸并爬去GitHub
- 10.2 Cookies池的搭建
- 11.App的爬取
- 11.1 Charles的使用
- 11.2 mitmproxy的使用
- 11.3 mitmdump“得到”App電子書信息
- 11.4 Appium的基本使用
- 11.5 Appnium爬取微信朋友圈
- 11.6 Appium+mitmdump爬取京東商品
- 12.pyspider框架的使用
- 12.1 pyspider框架介紹
- 12.2 pyspider的基本使用
- 12.3 pyspider用法詳解
- 13.Scrapy框架的使用
- 13.1 scrapy框架介紹
- 13.2 入門
- 13.3 selector的用法
- 13.4 spider的用法
- 13.5 Downloader Middleware的用法
- 13.6 Spider Middleware的用法
- 13.7 Item Pipeline的用法
- 13.8 Scrapy對接Selenium
- 13.9 Scrapy對接Splash
- 13.10 Scrapy通用爬蟲
- 13.11 Scrapyrt的使用
- 13.12 Scrapy對接Docker
- 13.13 Scrapy爬取新浪微博
- 14.分布式爬蟲
- 14.1 分布式爬蟲原理
- 14.2 Scrapy-Redis源碼解析
- 14.3 Scrapy分布式實現
- 14.4 Bloom Filter的對接
- 15.分布式爬蟲的部署
- 15.1 Scrapyd分布式部署
- 15.2 Scrapyd-Client的使用
- 15.3 Scrapyd對接Docker
- 15.4 Scrapyd批量部署
- 15.5 Gerapy分布式管理
- 微信公總號文章實戰
- 源碼
- other