在連線mysql資料庫時,採用的是pymysql庫
執行結果如下import pymysql
db = pymysql.connect(host=
"192.168.218.129"
,user=
"root"
,password=
"11111111"
,database=
"pymysql"
,port=
3306
)# 使用cursor()方法獲取操作游標
cursor = db.cursor(
)# 使用execute方法執行sql語句
cursor.execute(
"select version()"
)# 使用 fetchone() 方法獲取一條資料
data = cursor.fetchone(
("database version :{}"
.format
(data)
)# 關閉資料庫連線
db.close(
)
python向資料庫中插入資料分為純文字插入和帶有變數插入
1、純文字插入
純文字插入指的是整個插入語句中包含有需要插入的資料,下面的user表中有id,name,age桑屬性,id是主鍵自增長,因此在插入資料時不用指定資料。
檢視資料庫db = pymysql.connect(host=
"192.168.218.129"
,user=
"root"
,password=
"11111111"
,database=
"pymysql"
,port=
3306
)cursor = db.cursor(
)sql =
'''insert into user(name,age) values ("ff",43)
'''cursor.execute(sql)
# 提交到資料庫執行
db.commit(
)db.close(
)
2、帶有變數插入
帶有變數插入只插入的資料儲存在變數中,在插入語句中使用%s
作為佔位符,在python中,無論是字串還是整型型別的資料,都是使用%s
作為佔位符
執行結果如下db = pymysql.connect(host=
"192.168.218.129"
,user=
"root"
,password=
"11111111"
,database=
"pymysql"
,port=
3306
)cursor = db.cursor(
)sql =
'''insert into user(name,age) values (%s,%s)
'''name =
"xiaofv"
age =
21cursor.execute(sql,
(name,age)
)# 提交到資料庫執行
db.commit(
)db.close(
)
python查詢mysql使用 fetchone() 方法獲取單條資料, 使用fetchall() 方法獲取多條資料。
fetchone
執行結果如下db = pymysql.connect(host=
"192.168.218.129"
,user=
"root"
,password=
"11111111"
,database=
"pymysql"
,port=
3306
)cursor = db.cursor(
)sql =
'''select * from user
'''name =
"xiaofv"
age =
21cursor.execute(sql)
# 提交到資料庫執行
data = cursor.fetchone(
(data)
db.close(
)
關於其他兩個這裡就不再展示
python簡單爬蟲(pycharm) 二
python簡單爬蟲 pycharm 二 我們來把他的文字,也就是 標籤下的東西給爬出來。比如這一段,注意那句 這裡選用beautifulsoup包。首先開啟cmd,進入安裝python的資料夾下的script資料夾 然後正常的安裝 pip install beautifulsoup4裝完長這樣 u...
pycharm實現scrapy爬蟲的生成和入門
雖然是用pycharm進行除錯,但是最開始一定不要在pycharm中生成專案,因為要用scrapy自己生成乙個專案,否則會缺少如同scrapy.cfg的配置檔案,導致unknown command crawl錯誤。所以先在自己想要的地方開始 scrapy startproject myproject...
python爬蟲練習,爬取資料寫入MySQL資料庫
本次爬取內容就選取章節名和章節鏈結作為舉例 資料庫操作的基本方法 1 連線資料庫 2 獲取資料庫游標 3 執行sql語句 4 斷開資料庫連線 連線資料庫,引數包括ip 使用者名稱 密碼 對應的庫名 connect pymysql.connect localhost root gui2019 pyth...