?
作者主頁:編程指南針
作者簡介:Java、前端、Python開發(fā)多年,做過高程,項(xiàng)目經(jīng)理,架構(gòu)師
主要內(nèi)容:Java項(xiàng)目開發(fā)、畢業(yè)設(shè)計(jì)開發(fā)、面試技術(shù)整理、最新技術(shù)分享
收藏點(diǎn)贊不迷路 關(guān)注作者有好處
文末獲得源碼
一,使用Python操作數(shù)據(jù)庫
數(shù)據(jù)庫作為存儲(chǔ)系統(tǒng)數(shù)據(jù)的主要工具,擔(dān)負(fù)著數(shù)據(jù)持久化存儲(chǔ)的重任,本次主要講解如何使用Python連接操作SQLite和MYSQL數(shù)據(jù)庫。本部分需要具有一定的數(shù)據(jù)庫基本知識(shí),比如數(shù)據(jù)庫的DML\DDL語句操作等,不再講述數(shù)據(jù)庫相關(guān)知識(shí)。
1.1 連接對象
數(shù)據(jù)庫連接對象主要提供獲取數(shù)據(jù)庫游標(biāo)對象和提交/回滾事務(wù)的方法,以及如何關(guān)閉數(shù)據(jù)庫連接。
python中使用connect()函數(shù)來獲得數(shù)據(jù)庫連接對象。
語法:
connect(server=None,user=None,password=None,database=None,charset=None)
連接示例:
import pymysql
con = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='test',
charset='utf8',
cursorclass=pymysql.cursors.DictCursor)
connect()函數(shù)返回連接對象,它提供了一些方法用于操作事務(wù)和游標(biāo):
close():關(guān)閉數(shù)據(jù)庫連接
commit():提交事務(wù)
rollback():回滾事務(wù)
cursor():獲取游標(biāo)對象,操作數(shù)據(jù)庫,執(zhí)行DML操作,調(diào)用存儲(chǔ)過程等
1.2 游標(biāo)對象
游標(biāo)對象(Cursor Object)代表數(shù)據(jù)庫中的游標(biāo),用于指示抓取數(shù)據(jù)操作的上下文,主要提供執(zhí)行SQL語句、調(diào)用存儲(chǔ)過程、獲取查詢結(jié)果等方法。
通過cursor()方法來獲得游標(biāo)對象。游標(biāo)對象有以下兩個(gè)常用的屬性:
* description:數(shù)據(jù)庫列類型和值的描述信息
* rowcount: 返回結(jié)果的行數(shù)統(tǒng)計(jì)信息,如SELECT,UPDATE,CALLPROC等
常用方法如下圖所示:
1.3 SQLite 數(shù)據(jù)庫
SQLite數(shù)據(jù)庫是一種嵌入式數(shù)據(jù)庫,它的數(shù)據(jù)庫就一個(gè)文件。它本身是使用C語言編寫的,體積小,所以經(jīng)常被集成到各種應(yīng)用程序中,Python就內(nèi)置了SQLite3,所以在Python中使用SQLite,不需要安裝任何模塊,直接使用。
1.3.1 創(chuàng)建數(shù)據(jù)庫文件
數(shù)據(jù)庫操作的基本流程圖如下圖所示。
示例:文章來源地址http://www.zghlxwxcb.cn/news/detail-689759.html
#操作SQLite數(shù)據(jù)庫
import sqlite3
conn = sqlite3.connect("mysoft.db") #如果不存會(huì)自動(dòng)創(chuàng)建mysoft.db
cursor = conn.cursor()
cursor.execute("create table user(id int(10) primary key,name varchar(20))")
#關(guān)閉游標(biāo)
cursor.close()
#關(guān)閉connection
conn.close()
IDEA中集成的有SQLite插件,可以直接雙擊打開創(chuàng)建的SQLite數(shù)據(jù)庫。具體如下圖所示:
1.3.2 數(shù)據(jù)操作
1.新增用戶數(shù)據(jù):
#操作SQLite數(shù)據(jù)庫
import sqlite3
conn = sqlite3.connect("mysoft.db") #如果不存會(huì)自動(dòng)創(chuàng)建mysoft.db
cursor = conn.cursor()
cursor.execute("insert into user(id,name) values('1','znz')")
cursor.execute("insert into user(id,name) values('2','znz001')")
cursor.execute("insert into user(id,name) values('3','znz002')")
conn.commit() #提交事務(wù)后數(shù)據(jù)才會(huì)進(jìn)入數(shù)據(jù)庫中
#關(guān)閉游標(biāo)
cursor.close()
#關(guān)閉connection
conn.close()
可在IDEA中的右側(cè)顯示SQLite處user表右鍵選擇Run SQL Script來執(zhí)行SQL查詢:
select * from user
2.查詢用戶數(shù)據(jù)
提供的三種常方式來進(jìn)行數(shù)據(jù)查詢:
* fetchone(): 獲得查詢結(jié)果集中的下一條記錄
* fetchmany(size): 獲取指定數(shù)量的記錄
* fetchall(): 獲取結(jié)構(gòu)集的所有記錄
示例:
#操作SQLite 數(shù)據(jù)查詢
import sqlite3
conn = sqlite3.connect("mysoft.db") #如果不存會(huì)自動(dòng)創(chuàng)建mysoft.db
cursor = conn.cursor()
cursor.execute("select * from user")
result = cursor.fetchone() #取第一條數(shù)據(jù)后,指針停留在第二條
print(result)
result1 = cursor.fetchmany(2) #取出剩下的兩條
print(result1)
result2 = cursor.fetchall() #再取就沒有了
print(result2)
輸出結(jié)果:
(1, 'znz')
[(2, 'znz001'), (3, 'znz002')]
[]
示例:
#操作SQLite 數(shù)據(jù)查詢
import sqlite3
conn = sqlite3.connect("mysoft.db") #如果不存會(huì)自動(dòng)創(chuàng)建mysoft.db
cursor = conn.cursor()
cursor.execute("select * from user")
result2 = cursor.fetchall()
print(result2)
conn.commit()
#關(guān)閉游標(biāo)
cursor.close()
#關(guān)閉connection
conn.close()
輸出結(jié)果:
[(1, 'znz'), (2, 'znz001'), (3, 'znz002')]
占位符傳參:可以通過?來表示一個(gè)參數(shù)的占位,實(shí)現(xiàn)運(yùn)行時(shí)動(dòng)態(tài)傳參
#操作SQLite 數(shù)據(jù)查詢
import sqlite3
conn = sqlite3.connect("mysoft.db") #如果不存會(huì)自動(dòng)創(chuàng)建mysoft.db
cursor = conn.cursor()
cursor.execute("select * from user where id>?",(1,))
result2 = cursor.fetchall()
print(result2)
conn.commit()
#關(guān)閉游標(biāo)
cursor.close()
#關(guān)閉connection
conn.close()
輸出結(jié)果:
[(2, 'znz001'), (3, 'znz002')]
3.修改用戶的數(shù)據(jù)
示例:
#操作SQLite 數(shù)據(jù)修改
import sqlite3
conn = sqlite3.connect("mysoft.db") #如果不存會(huì)自動(dòng)創(chuàng)建mysoft.db
cursor = conn.cursor()
cursor.execute("update user set name=? where id=?",('fxp',1,))
conn.commit()
cursor.execute("select * from user")
result = cursor.fetchall()
print(result)
#關(guān)閉游標(biāo)
cursor.close()
#關(guān)閉connection
conn.close()
4.刪除用戶數(shù)據(jù)
示例:
#操作SQLite 數(shù)據(jù)修改
import sqlite3
conn = sqlite3.connect("mysoft.db") #如果不存會(huì)自動(dòng)創(chuàng)建mysoft.db
cursor = conn.cursor()
cursor.execute("delete from user where id=?",(1,))
conn.commit()
cursor.execute("select * from user")
result = cursor.fetchall()
print(result)
#關(guān)閉游標(biāo)
cursor.close()
#關(guān)閉connection
conn.close()
1.4 MYSQL數(shù)據(jù)庫
本次使用MYSQL5.7版本數(shù)據(jù)庫,安裝參考演示視頻:https://live.csdn.net/v/282244
python操作MYSQL數(shù)據(jù)庫,需要支持Python的MySQL驅(qū)動(dòng)來連接到MySQL服務(wù)器,我們常用PyMySQL模塊來操作MYSQL數(shù)據(jù)庫。需在線安裝PyMySQL模塊:
pip install PyMySQL
我們通過MYSQL的客戶端工具Navicat來連接MYSQL服務(wù)器后,可以創(chuàng)建一個(gè)名為studentPython的數(shù)據(jù)庫。
然后 就可以編寫代碼連接MYSQL進(jìn)行相應(yīng)操作了。
示例:
#操作MYSQL數(shù)據(jù)庫
import pymysql
#此處傳參最好是使用關(guān)鍵字參數(shù),不同版本的connect傳的不太一樣
conn = pymysql.connect(host="localhost",user="root",password="root",db="studentPython")
cursor = conn.cursor()
cursor.execute("select version()")
result = cursor.fetchone()
print("database version:%s" % result)
#關(guān)閉游標(biāo)
cursor.close()
#關(guān)閉connection
conn.close()
1.創(chuàng)建數(shù)據(jù)表
在數(shù)據(jù)庫操作中,創(chuàng)建表,刪除表這都屬于DDL語句,也就是數(shù)據(jù)結(jié)構(gòu)定義語句。
示例:
#操作MYSQL數(shù)據(jù)庫 創(chuàng)建表
import pymysql
conn = pymysql.connect(host="localhost",user="root",password="root",db="studentPython")
cursor = conn.cursor()
cursor.execute("DROP TABLE IF EXISTS books")
#使用預(yù)處理語句創(chuàng)建表
sql="""
create table books(
id int(8) NOT NULL AUTO_INCREMENT,
name varchar(50) NOT NULL,
category varchar(50) NOT NULL,
price decimal (10,2) DEFAULT NULL,
publish_time date DEFAULT NULL,
primary key(id)
)
"""
#執(zhí)行SQL語句
cursor.execute(sql)
#關(guān)閉游標(biāo)
cursor.close()
#關(guān)閉connection
conn.close()
2.操作MYSQL表
對表的增刪改查操作和SQLite一樣,下面舉例演示使用 executemany()方法批量插入數(shù)據(jù)。文章來源:http://www.zghlxwxcb.cn/news/detail-689759.html
示例:
#操作MYSQL數(shù)據(jù)庫 操作表
import pymysql
conn = pymysql.connect(host="localhost",user="root",password="root",db="studentPython")
cursor = conn.cursor()
#數(shù)據(jù)列表
data =[
("零基礎(chǔ)學(xué)Python","python",'79.80','2018-5-28'),
("Python從入門到精通","python",'69.80','2018-5-28'),
("零基礎(chǔ)學(xué)PHP","php",'79.80','2018-5-28'),
("零基礎(chǔ)學(xué)Java","java",'59.80','2018-5-28'),
]
try:
cursor.executemany("insert into books(name,category,price,publish_time) values(%s,%s,%s,%s)",data)
#提交數(shù)據(jù)
conn.commit()
except:
#發(fā)生錯(cuò)誤時(shí)回滾
conn.rollback()
#關(guān)閉游標(biāo)
cursor.close()
#關(guān)閉connection
conn.close()
到了這里,關(guān)于零基礎(chǔ)學(xué)Python|Python高階-使用Python操作數(shù)據(jù)庫的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!