1、安裝pymysql庫
如果你想要使用python操作MySQL數(shù)據(jù)庫,就必須先要安裝pymysql庫,這個庫的安裝很簡單,直接使用pip install pymysql;進(jìn)行安裝。
假如上面這種方式還是安裝不上,就用如下鏈接找一個合適的安裝包進(jìn)行安裝,這個就不細(xì)說了,請自行百度。
https://www.lfd.uci.edu/~gohlke/pythonlibs/
2、使用python連接mysql數(shù)據(jù)庫
1)六個常用的連接參數(shù)
參數(shù)host:mysql服務(wù)器所在的主機(jī)的ip;
參數(shù)user:用戶名
參數(shù)password:密碼
參數(shù)port:連接的mysql主機(jī)的端口,默認(rèn)是3306
參數(shù)db:連接的數(shù)據(jù)庫名
參數(shù)charset:當(dāng)讀取數(shù)據(jù)出現(xiàn)中文會亂碼的時候,需要我們設(shè)置一下編碼;我們使用python操作數(shù)據(jù)庫的時候,那么python就相當(dāng)于是client,
我們是用這個client來操作mysql的server服務(wù)器,python3默認(rèn)采用的utf8字符集,我的mysql服務(wù)器默認(rèn)采用latin1字符集,
因此mysql中創(chuàng)建的每張表,都是建表的時候加了utf8編碼的,因此這里設(shè)置的應(yīng)該就是connection連接器的編碼。
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服務(wù)器安裝在哪里,由于我的mysql就是安裝在本機(jī)上,因此這里可以寫localhost,我也可以寫成主機(jī)名或者主機(jī)ip。
db指的是你要操作的是哪一個數(shù)據(jù)庫,在進(jìn)行數(shù)據(jù)庫連接的時候,最好加上這個參數(shù)。
3)一個簡單的熱身案例
# 導(dǎo)包
import pymysql
# 使用pymysql連接上mysql數(shù)據(jù)庫服務(wù)器,創(chuàng)建了一個數(shù)據(jù)庫對象;
db = pymysql.connect(host='localhost',user='root', password='123456',
port=3306, db='huangwei', charset='utf8')
# 開啟mysql的游標(biāo)功能,創(chuàng)建一個游標(biāo)對象;
cursor = db.cursor()
# 要執(zhí)行的SQL語句;
sql = "select * from student"
# 使用游標(biāo)對象執(zhí)行SQL語句;
cursor.execute(sql)
# 使用fetchone()方法,獲取返回的結(jié)果,但是需要用變量保存返回結(jié)果;
data = cursor.fetchone()
print(data)
# 斷開數(shù)據(jù)庫的連接,釋放資源;
db.close()
結(jié)果如下:
3、cursor游標(biāo)對象的一些常用方法
1)cursor用來執(zhí)行命令的方法
execute(query, args):執(zhí)行單條sql語句,接收的參數(shù)為sql語句本身和使用的參數(shù)列表,返回值為受影響的行數(shù);
executemany(query, args):執(zhí)行單挑sql語句,但是重復(fù)執(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)建一個游標(biāo)對象;
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語句怎么寫,在這里就怎么寫。還有一個細(xì)節(jié)需要注意的是,在python中,將代碼進(jìn)行多次換行的時候,最好使用“三引號”。
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進(jìn)行操作
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模塊是默認(rèn)開啟mysql的事務(wù)功能的,因此,進(jìn)行 “增” “刪” "改"的時候,一定要使用db.commit()提交事務(wù),否則就看不見所插入的數(shù)據(jù)。
??② 進(jìn)行 “增”、“刪”、"改"的時候,一定要使用try…except…語句,因?yàn)槿f一沒插入成功,其余代碼都無法執(zhí)行。當(dāng)語句執(zhí)行不成功,我們就db.rollback()回滾到操作之前的狀態(tài);當(dāng)語句執(zhí)行成功,我們就db.commit()提交事務(wù)。
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()
很多小伙伴在學(xué)習(xí)Python的過程中往往因?yàn)闆]有資料或者沒人指導(dǎo)從而導(dǎo)致自己不想學(xué)下去了,因此我特意準(zhǔn)備了大量的PDF書籍、視頻教程,都免費(fèi)送給大家!不管你是零基礎(chǔ)還是有基礎(chǔ)都可以獲取到自己相對應(yīng)的學(xué)習(xí)禮包!包括Python軟件工具和2019最新入門到實(shí)戰(zhàn)教程,(https://url.cn/59RWE1Z)復(fù)制到瀏覽器打開!