使用Python實(shí)現(xiàn)Mysql數(shù)據(jù)庫相關(guān)操作詳解
前言:
前面學(xué)習(xí)了MySQL的基礎(chǔ)語句,就有人會(huì)問,那怎么去通過編程語言來操作mysql數(shù)據(jù)庫呢,這總不能只能用sql指令來去操作吧?答案是肯定可以通過編程語言去操作的,只是sql指令是操作數(shù)據(jù)庫的基礎(chǔ)指令,編程語言只是其輔助作用的,把數(shù)據(jù)庫與其他程序進(jìn)行結(jié)合。那這一期我就來講解怎么去通過Python去連接MySQL數(shù)據(jù)庫,同時(shí)實(shí)現(xiàn)數(shù)據(jù)庫等相關(guān)操作
pymysql
什么是pymysql
pymysql是Python中操作數(shù)據(jù)庫的第三方模塊,通過這個(gè)模塊的相關(guān)方法,我們可以連接并且去操作mysql數(shù)據(jù)庫。
安裝
進(jìn)入cmd,然后輸入
pip install pymysql
等待一段時(shí)間就會(huì)安裝好了的,然后輸入 pip list查看是否安裝好,如圖所示(說明已經(jīng)安裝好了):
好了,安裝完成了之后就開始寫代碼了。
測試連接數(shù)據(jù)庫
導(dǎo)入模塊
import pymysql as psql
測試連接查詢操作
import pymysql as psql #連接數(shù)據(jù)庫 db=psql.connect( host='localhost', #這里是表示數(shù)據(jù)庫地址 user='heweijie', #這里是表示用戶名 password='heweijie', #這里是表示password database='hello', #這里是表示要連接的數(shù)據(jù)庫名字 charset='utf8' #這里是字符編碼,一般都選utf8 ) #創(chuàng)建讀取游標(biāo) cur=db.cursor() sql=r'select version();' #sql語句,查看mysql版本 cur.execute(sql) #執(zhí)行sql語句 data=cur.fetchone() #返回一條信息 print(data) cur.close() #關(guān)閉游標(biāo) db.close() #關(guān)閉數(shù)據(jù)庫的連接 #輸出結(jié)果:('8.0.30',)
這里可以看我們成功連接了數(shù)據(jù)庫,同時(shí)返回一條結(jié)果,要注意,當(dāng)我們?nèi)ソY(jié)束使用數(shù)據(jù)庫的時(shí)候要記得去關(guān)閉數(shù)據(jù)庫的連接,免得造成數(shù)據(jù)庫的數(shù)據(jù)泄露等問題。
connect() 方法參數(shù)
參數(shù) | 說明 |
host= | 數(shù)據(jù)庫連接地址 |
user= | 數(shù)據(jù)庫用戶名 |
password= | 數(shù)據(jù)庫password |
database= | 要連接的數(shù)據(jù)庫名字 |
port=3306 | 連接端口,一般玩3306 |
charset=utf8 | 設(shè)置字符集,一般為utf8 |
connect_timeout=10 | 連接數(shù)據(jù)庫超時(shí)時(shí)間,一般默認(rèn)為10秒 |
dsn | 數(shù)據(jù)源名稱,給出該參數(shù)表示數(shù)據(jù)庫依賴 |
返回結(jié)果fecthone、fecthmany、fecthall
當(dāng)我們?nèi)?zhí)行sql查詢指令的時(shí)候,我們要獲取到返回的結(jié)果,但是返回的結(jié)果可以是單行,也可以是自定義多行,也可以是返回全部結(jié)果,要想實(shí)現(xiàn)這樣的效果我們就要要用到fecthone、fecthmany、fecthall 這三個(gè)方法了。下面看例子
當(dāng)前數(shù)據(jù)庫表信息:
#創(chuàng)建讀取游標(biāo) cur=db.cursor() sql=r'select *from user' #sql語句,查看mysql版本 cur.execute(sql) #執(zhí)行sql語句 #返回一條信息 data1=cur.fetchone() print('fecthone>>>',data1) #返回自定義條數(shù) data2=cur.fetchmany(5) print('fetchmany>>>',data2) #返回全部信息 data3=cur.fetchall() print('fecthall>>>',data3)
這時(shí)你們會(huì)發(fā)現(xiàn)一個(gè)現(xiàn)象,每次返回信息后,再次獲取信息時(shí),就不會(huì)再返回這條信息了,而是接著往下讀取。這里跟文本文件讀取是一樣的,游標(biāo)cur是往下讀取的,所以前面已經(jīng)獲取到的信息就不再會(huì)返回。如果你想返回前面的信息話,你可以重新創(chuàng)建游標(biāo),執(zhí)行新的指令就OK了。
創(chuàng)建和管理數(shù)據(jù)庫
sql指令是操作數(shù)據(jù)庫的基礎(chǔ)指令,而編程語言是起輔助作用的,所以真正意義上操作數(shù)據(jù)庫的是sql指令,我們通過編程語言只是去把獲取到的信息進(jìn)行處理。這里就來看看怎么去通過Python來去創(chuàng)建一個(gè)數(shù)據(jù)庫
import pymysql as psql class Database: '''通過面對(duì)對(duì)象的方式去創(chuàng)建一個(gè)數(shù)據(jù)庫以及 實(shí)現(xiàn)數(shù)據(jù)庫管理操作方法''' def __init__(self): self.db=psql.connect( host='localhost', user='heweijie', password='heweijie', charset='utf8' ) #操作游標(biāo) self.cur = self.db.cursor() def create(self,name): '''創(chuàng)建一個(gè)數(shù)據(jù)庫,名字為name,自行輸入''' try: sql=fr'create database if not exists {name}' self.cur.execute(sql) except Exception as e: print(e) print('創(chuàng)建失敗') self.db.rollback() #事物的回滾操作,就是回到開始 def showdatabases(self): '''查看全部數(shù)據(jù)庫名字''' sql=r'show databases' self.cur.execute(sql) result=self.cur.fetchall() return result #刪除數(shù)據(jù)庫 def dropdatabase(self,name): try: sql=fr'drop database {name}' self.cur.execute(sql) except Exception as e: print(e) print('刪除失敗') self.db.rollback() def close(self): '''關(guān)閉連接,結(jié)束操作''' self.cur.close() self.db.close() #操作示例: if __name__ == '__main__': d=Database() d.create('fucc') print(d.showdatabases()) d.dropdatabase('fucc') print(d.showdatabases()) d.close()
表的創(chuàng)建和增刪改查
表是數(shù)據(jù)庫里面儲(chǔ)存容器,數(shù)據(jù)基本上是儲(chǔ)存到表里頭,下面通過創(chuàng)建表操作對(duì)象去對(duì)表中的數(shù)據(jù)進(jìn)行操作。
1.創(chuàng)建表
創(chuàng)建一個(gè)表,首先要連接到數(shù)據(jù)庫,獲取到當(dāng)前的數(shù)據(jù)庫db,然后輸入sql指令來去創(chuàng)建表,sql 指令:create table if not exists 表名(……表結(jié)構(gòu)……);
def connect(database_name): db = psql.connect( host='127.0.0.1', user='heweijie', password='heweijie', port=3306, database=database_name, charset='utf8' ) return db #返回當(dāng)前連接的數(shù)據(jù)庫 def createtable(name): db=connect('test') #數(shù)據(jù)庫名字為test cur=db.cursor() try: sql=f'create table if not exists {name}(id int primary key auto_increment,name char(50),num int);' print('創(chuàng)建成功') except Exception as e: print(e) db.rollback()
2.查看表結(jié)構(gòu)
sql 指令是 :desc 表名;
#……………… def desctable(name): #表的名字為name db=connect('test') cur=db.cursor() sql=f'desc {name}' cur.execute(sql) print(cur.fetchall()) #輸出全部結(jié)果
3.查看全部表
sql 指令: show tables;
#………… def showtables(): db=connect('test') cur=db.cursor() sql='show tables;' cur.execute(sql) print(cur.fetchall())
4.刪除表
sql 指令:drop table 表名;
#……………… def droptable(name): db = connect('test') cur = db.cursor() try: sql = f'drop table {name};' cur.execute(sql) print('刪除成功') except Exception as e: print(e) db.rollback()
5.面向?qū)ο髮懛?/h3>
#創(chuàng)建表以及操作
class Table(object):
def __init__(self,database_name):
'''連接數(shù)據(jù)庫database_name,自寫'''
self.db=psql.connect(
host='127.0.0.1',
user='heweijie',
password='heweijie',
port=3306,
database=database_name,
charset='utf8'
)
self.cur=self.db.cursor()
def create(self,sql):
'''創(chuàng)建表,sql語句自行寫入'''
try:
self.cur.execute(sql)
print('create successfully')
except Exception as e:
print(e)
self.db.rollback()
def desctable(self,table):
'''查看表結(jié)構(gòu)'''
sql=fr'desc {table};'
self.cur.execute(sql)
result=self.cur.fetchall()
print(result)
def showtables(self):
'''查看這個(gè)數(shù)據(jù)庫里面的全部表'''
sql=f'show tables;'
self.cur.execute(sql)
result=self.cur.fetchall()
print(result)
def droptable(self,name):
'''把名字為name的表刪除'''
try:
sql=f'drop table {name};'
self.cur.execute(sql)
except Exception as e:
print(e)
self.db.rollback()
def insert(self,sql):
'''插入數(shù)據(jù),sql語句自寫'''
try:
self.cur.execute(sql)
except Exception as e:
print(e)
self.db.rollback()
def selectdata(self,sql):
'''查詢數(shù)據(jù),sql語句自寫'''
self.cur.execute(sql)
result=self.cur.fetchall()
print(result)
#使用示例
if __name__ == '__main__':
user=Table('hello')
user.create(r'create table if not exists mydatabase (id int primary key auto_increment,name char(50),num int);')
user.showtables()
user.desctable('mydatabase')
user.selectdata('select *from user;')#user 是另外一個(gè)表
user.droptable('mydatabase')
user.showtables()
#創(chuàng)建表以及操作 class Table(object): def __init__(self,database_name): '''連接數(shù)據(jù)庫database_name,自寫''' self.db=psql.connect( host='127.0.0.1', user='heweijie', password='heweijie', port=3306, database=database_name, charset='utf8' ) self.cur=self.db.cursor() def create(self,sql): '''創(chuàng)建表,sql語句自行寫入''' try: self.cur.execute(sql) print('create successfully') except Exception as e: print(e) self.db.rollback() def desctable(self,table): '''查看表結(jié)構(gòu)''' sql=fr'desc {table};' self.cur.execute(sql) result=self.cur.fetchall() print(result) def showtables(self): '''查看這個(gè)數(shù)據(jù)庫里面的全部表''' sql=f'show tables;' self.cur.execute(sql) result=self.cur.fetchall() print(result) def droptable(self,name): '''把名字為name的表刪除''' try: sql=f'drop table {name};' self.cur.execute(sql) except Exception as e: print(e) self.db.rollback() def insert(self,sql): '''插入數(shù)據(jù),sql語句自寫''' try: self.cur.execute(sql) except Exception as e: print(e) self.db.rollback() def selectdata(self,sql): '''查詢數(shù)據(jù),sql語句自寫''' self.cur.execute(sql) result=self.cur.fetchall() print(result) #使用示例 if __name__ == '__main__': user=Table('hello') user.create(r'create table if not exists mydatabase (id int primary key auto_increment,name char(50),num int);') user.showtables() user.desctable('mydatabase') user.selectdata('select *from user;')#user 是另外一個(gè)表 user.droptable('mydatabase') user.showtables()
到此這篇關(guān)于使用Python實(shí)現(xiàn)Mysql數(shù)據(jù)庫相關(guān)操作詳解的文章就介紹到這了,更多相關(guān)Python操作Mysql數(shù)據(jù)庫內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python使用Apache Kafka時(shí)Poll拉取速度慢的解決方法
在使用Apache Kafka時(shí),poll方法拉取消息速度慢常見于網(wǎng)絡(luò)延遲、消息大小過大、消費(fèi)者配置不當(dāng)或高負(fù)載情況,本文提供了優(yōu)化消費(fèi)者配置、并行消費(fèi)、優(yōu)化消息處理邏輯和監(jiān)控調(diào)試的解決方案,并附有Python代碼示例和相關(guān)類圖、序列圖以幫助理解和實(shí)現(xiàn)2024-09-09如何解決安裝包過程中的Requirement already satisfied:問題
這篇文章主要介紹了如何解決安裝包過程中的Requirement already satisfied:問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11python實(shí)現(xiàn)發(fā)送QQ郵件(可加附件)
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)發(fā)送QQ郵件,可添加附件功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-12-12如何在Python中實(shí)現(xiàn)goto語句的方法
這篇文章主要介紹了如何在Python中實(shí)現(xiàn)goto語句的方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05Pandas時(shí)間序列:時(shí)期(period)及其算術(shù)運(yùn)算詳解
今天小編就為大家分享一篇Pandas時(shí)間序列:時(shí)期(period)及其算術(shù)運(yùn)算詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-02-02python3+PyQt5重新實(shí)現(xiàn)QT事件處理程序
這篇文章主要為大家詳細(xì)介紹了python3+PyQt5重新實(shí)現(xiàn)QT事件處理程序,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-04-04