python與mysql數(shù)據(jù)庫交互的實現(xiàn)
1、安裝pymysql庫
如果你想要使用python操作MySQL數(shù)據(jù)庫,就必須先要安裝pymysql庫,這個庫的安裝很簡單,直接使用pip install pymysql;進行安裝。
假如上面這種方式還是安裝不上,就用如下鏈接找一個合適的安裝包進行安裝,這個就不細說了,請自行百度。
https://www.lfd.uci.edu/~gohlke/pythonlibs/
學習本篇文章,最好是先看我另外一篇關于游標cursor講解的文章,這樣會有更好的效果:http://www.dhdzp.com/article/177865.htm
2、使用python連接mysql數(shù)據(jù)庫
1)六個常用的連接參數(shù)
- 參數(shù)host:mysql服務器所在的主機的ip;
- 參數(shù)user:用戶名
- 參數(shù)password:密碼
- 參數(shù)port:連接的mysql主機的端口,默認是3306
- 參數(shù)db:連接的數(shù)據(jù)庫名
- 參數(shù)charset:當讀取數(shù)據(jù)出現(xiàn)中文會亂碼的時候,需要我們設置一下編碼;我們使用python操作數(shù)據(jù)庫的時候,那么python就相當于是client,我們是用這個client來操作mysql的server服務器,python3默認采用的utf8字符集,我的mysql服務器默認采用latin1字符集,因此mysql中創(chuàng)建的每張表,都是建表的時候加了utf8編碼的,因此這里設置的應該就是connection連接器的編碼。
什么是connection?可以參考我的另外一篇文章學習。
http://www.dhdzp.com/article/177872.htm
2)python連接mysql的語法
import pymysql db = pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='spiders',charset=' utf8')
- 最基本的參數(shù)是host,user,password和port,必須要有。剩下兩個參數(shù)根據(jù)你自己的情況決定是否使用。
- host指的是mysql服務器安裝在哪里,由于我的mysql就是安裝在本機上,因此這里可以寫localhost,我也可以寫成主機名或者主機ip。
- db指的是你要操作的是哪一個數(shù)據(jù)庫,在進行數(shù)據(jù)庫連接的時候,最好加上這個參數(shù)。
3)一個簡單的熱身案例
# 導包
import pymysql
# 使用pymysql連接上mysql數(shù)據(jù)庫服務器,創(chuàng)建了一個數(shù)據(jù)庫對象;
db = pymysql.connect(host='localhost',user='root', password='123456',
port=3306, db='huangwei', charset='utf8')
# 開啟mysql的游標功能,創(chuàng)建一個游標對象;
cursor = db.cursor()
# 要執(zhí)行的SQL語句;
sql = "select * from student"
# 使用游標對象執(zhí)行SQL語句;
cursor.execute(sql)
# 使用fetchone()方法,獲取返回的結(jié)果,但是需要用變量保存返回結(jié)果;
data = cursor.fetchone()
print(data)
# 斷開數(shù)據(jù)庫的連接,釋放資源;
db.close()
結(jié)果如下:

3、cursor游標對象的一些常用方法
1)cursor用來執(zhí)行命令的方法
- execute(query, args):執(zhí)行單條sql語句,接收的參數(shù)為sql語句本身和使用的參數(shù)列表,返回值為受影響的行數(shù);
- executemany(query, args):執(zhí)行單挑sql語句,但是重復執(zhí)行參數(shù)列表里的參數(shù),返回值為受影響的行數(shù);
2)cursor用來接收返回值的方法
- fetchone():返回一條結(jié)果行;
- fetchmany(size):接收size條返回結(jié)果行。如果size的值大于返回的結(jié)果行的數(shù)量,則會返回cursor.arraysize條數(shù)據(jù);
- fetchall():接收全部的返回結(jié)果行;
4、創(chuàng)建表
import pymysql db = pymysql.connect(host='localhost',user='root', password='123456',port=3306, db='huangwei', charset='utf8') # 創(chuàng)建一個游標對象; cursor = db.cursor() # 建表語句; sql = """ create table person( id int auto_increment primary key not null, name varchar(10) not null, age int not null )charset=utf8 """ # 執(zhí)行sql語句; cursor.execute(sql) # 斷開數(shù)據(jù)庫的連接; db.close()
注意:你在mysql中sql語句怎么寫,在這里就怎么寫。還有一個細節(jié)需要注意的是,在python中,將代碼進行多次換行的時候,最好使用“三引號”。
5、查詢數(shù)據(jù)…查
1)fetchone():一次獲取一條記錄
import pymysql
db = pymysql.connect(host='localhost',user='root',db='huangwei',password='123456',port=3306,charset='utf8')
cursor = db.cursor()
cursor.execute('select count(*) from person')
aa = cursor.fetchone()
print(aa)
cursor.execute('select name,age from person')
for i in range(aa[0]):
a,b = cursor.fetchone()
c = "我的名字叫{},今年{}歲".format(a,b)
display(c)
db.close()
結(jié)果如下:

2)fetchall():一次獲取所有記錄
import pymysql
db = pymysql.connect(host='localhost',user='root',db='huangwei',password='123456',port=3306,charset='utf8')
cursor = db.cursor()
cursor.execute('select name,age from person')
aa = cursor.fetchall()
# print(aa)
for a,b in aa:
c = "我的名字叫{},今年{}歲".format(a,b)
display(c)
db.close()
結(jié)果如下:

注:還有一個fetchmany()方法,用于一次性獲取指定條數(shù)的記錄,請自行下去研究。
3)使用pandas中的read_sql()方法,將提取到的數(shù)據(jù)直接轉(zhuǎn)化為DataFrame進行操作
import pymysql
import pandas as pd
db = pymysql.connect(host='localhost',user='root',db='huangwei',password='123456',port=3306,charset='utf8')
cursor = db.cursor()
df1 = pd.read_sql("select * from student where ssex='男'",db)
display(df1)
df2 = pd.read_sql("select * from student where ssex='女'",db)
display(df2)
結(jié)果如下:

6、插入數(shù)據(jù)…增
1)一次性插入一條數(shù)據(jù)
import pymysql
db = pymysql.connect(host='localhost',user='root', password='123456',port=3306, db='huangwei', charset='utf8')
cursor = db.cursor()
# mysql中SQL語句怎么寫,這里就怎么寫;
name = "豬八戒"
age = 8000
sql = 'insert into person(name,age) values ("豬八戒",8000)'
try:
cursor.execute(sql)
db.commit()
print("插入成功")
except:
print("插入失敗")
db.rollback()
db.close()
1.1)一次性插入一條數(shù)據(jù)
import pymysql
db = pymysql.connect(host='localhost',user='root', password='123456',port=3306, db='huangwei', charset='utf8')
cursor = db.cursor()
# 插入數(shù)據(jù)
sql = 'insert into person(name,age) values(%s,%s)'
try:
cursor.execute(sql,('孫悟空',100000))
db.commit()
print("插入成功")
except:
print("插入失敗")
db.rollback()
db.close()
2)一次性插入多條數(shù)據(jù)
import pymysql
db = pymysql.connect(host='localhost',user='root', password='123456',port=3306, db='huangwei', charset='utf8')
cursor = db.cursor()
# 插入數(shù)據(jù)
sql = 'insert into person(name,age) values(%s,%s)'
# 注意:(('牛魔王',9000),('鐵扇公主',8000),('玉皇大帝',6000))也可以,小括號都可以換為中括號
datas = [('牛魔王',9000),('鐵扇公主',8000),('玉皇大帝',6000)]
try:
cursor.executemany(sql,datas)
db.commit()
print("插入成功")
except:
print("插入失敗")
db.rollback()
db.close()
總結(jié)如下:
① pymysql模塊是默認開啟mysql的事務功能的,因此,進行 “增” “刪” "改"的時候,一定要使用db.commit()提交事務,否則就看不見所插入的數(shù)據(jù)。
② 進行 “增”、“刪”、"改"的時候,一定要使用try…except…語句,因為萬一沒插入成功,其余代碼都無法執(zhí)行。當語句執(zhí)行不成功,我們就db.rollback()回滾到操作之前的狀態(tài);當語句執(zhí)行成功,我們就db.commit()提交事務。
7、更新數(shù)據(jù)…改
import pymysql
db = pymysql.connect(host='localhost',user='root', password='123456',port=3306, db='huangwei', charset='utf8')
cursor = db.cursor()
# 更新數(shù)據(jù)
sql = 'update person set age=%s where name=%s'
try:
cursor.execute(sql,[90000,"玉皇大帝"])
db.commit()
print("更新成功")
except:
print("更新失敗")
db.rollback()
db.close()
8、刪除數(shù)據(jù)…刪
import pymysql
db = pymysql.connect(host='localhost',user='root', password='123456',port=3306, db='huangwei', charset='utf8')
cursor = db.cursor()
# 刪除數(shù)據(jù)
sql = 'delete from person where age=8000'
try:
cursor.execute(sql)
db.commit()
print("刪除成功")
except:
print("刪除失敗")
db.rollback()
db.close()
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
python實現(xiàn)自動獲取IP并發(fā)送到郵箱
這篇文章主要為大家詳細介紹了python實現(xiàn)自動獲取IP并發(fā)到郵箱,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-12-12
Python字典刪除鍵值對和元素的四種方法(小結(jié))
刪除列表或者字符串元素的方法不止一種,同樣,刪除字典元素的方法也不止一種,本文主要介紹python中刪除字典元素的四種方法:1、使用del語句;2、使用clear();3、使用pop();4、使用popitem()。感興趣的可以了解一下2021-12-12
pyqt 實現(xiàn)為長內(nèi)容添加滑輪 scrollArea
今天小編就為大家分享一篇pyqt 實現(xiàn)為長內(nèi)容添加滑輪 scrollArea,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06
python 提取tuple類型值中json格式的key值方法
今天小編就為大家分享一篇python 提取tuple類型值中json格式的key值方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12
python結(jié)合多線程爬取英雄聯(lián)盟皮膚(原理分析)
多線程是為了同步完成多項任務,不是為了提高運行效率,而是為了提高資源使用效率來提高系統(tǒng)的效率。這篇文章主要介紹了python爬取英雄聯(lián)盟皮膚結(jié)合多線程的方法,需要的朋友可以參考下2021-05-05

