python操作數(shù)據(jù)庫需要用到第三方庫某饰,本人目前使用的是PyCharm作為編譯工具透硝,寫python的大多數(shù)人應(yīng)該都用的是這個檩咱。關(guān)于它的一些使用技巧可以參考PyCharm使用筆記次员,在此不做贅述蔗候。
安裝MySQL的第三方庫
File --> Setting --> Project:項目名 --> Project Interpreter 點擊頁面中的+號,在出現(xiàn)的搜素框中輸入自己查找的第三庫名稱即可柑潦,最后單擊左下方的Install Package開始安裝享言。安裝成功會出現(xiàn)如圖展示的綠色提示信息,即表示安裝成功渗鬼,在代碼中導(dǎo)入使用即可览露。
安裝第三方庫
如果安裝失敗,則進入終端通過pip命令
pip install MySQL(或者其它你安裝失敗的第三庫名)
來進行安裝譬胎。之后在通過配置運行python的環(huán)境即可差牛。但要注意建立的python項目中不要出現(xiàn)與第三庫同名的文件命锄,否則導(dǎo)入的時候根據(jù)優(yōu)先級它會先導(dǎo)入你所創(chuàng)建的文件。
具體操作見如下代碼和其中注釋:
import pymysql
# 第一步偏化,連接數(shù)據(jù)庫脐恩,類似于指令里面的 mysql -uroot -p
# mysql -h地址 -uroot -p
'''
連接數(shù)據(jù)庫需要用到的參數(shù)
主機:host
端口:port
用戶名:user
密碼:password
指定數(shù)據(jù)庫:db
指定字符集:charset
'''
db = pymysql.connect(host='localhost', port=3306, user='root', password='root', db='ghope', charset='utf8')
# 連接成功之后,得到一個對象
# print(db)
# 首先根據(jù)db得到游標侦讨,游標就是執(zhí)行sql語句用到的東西
# cursor = db.cursor()
# 給cursor添加一個參數(shù)驶冒,讓其的到數(shù)據(jù)是一個字典
cursor = db.cursor(cursor=pymysql.cursors.DictCursor)
# 準備sql語句,執(zhí)行sql語句
sql = 'select * from star'
# 返回結(jié)果rows是受影響的行數(shù)
rows = cursor.execute(sql)
# print(rows)
# 通過cursor的方法得到數(shù)據(jù)
# 返回一個元組韵卤,元組里面每個元素的值對應(yīng)的就是數(shù)據(jù)表中每個字段對應(yīng)的值
# 獲取內(nèi)容的時候骗污,里面有個迭代器在記錄你的位置
# print(cursor.fetchone())
# print(cursor.fetchone())
# print(cursor.fetchone())
# print(cursor.fetchone())
# print(cursor.fetchmany(5))
# print(cursor.fetchmany(5))
# 元組里面套元組
# print(cursor.fetchall())
# 打印得到所有的用戶名
ret = cursor.fetchall()
for obj in ret:
print('我叫%s,我來自%s,我有%s¥' % (obj['name'], obj['province'], obj['money']))
# print(ret)
# 遍歷每一個元組
# for tp in ret:
# print(tp[1])
# 最后呀,要記得關(guān)閉
cursor.close()
db.close()
上述代碼運行結(jié)果
增加代碼健壯性
import pymysql
db = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='ghope', charset='utf8')
# print(db)
cursor = db.cursor()
sql = 'select * from start'
# 查詢語句沈条,通過try-except需忿,讓代碼更加健壯
try:
ret = cursor.execute(sql)
print(cursor.fetchall())
except Exception as e:
print(e)
finally:
cursor.close()
db.close()
增加數(shù)據(jù)安全性
import pymysql
db = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='ghope', charset='utf8')
cursor = db.cursor()
'''
# 準備sql語句
obj = {'name': '李云龍', 'money': '20', 'province': '河南', 'age': 36, 'sex': '男'}
# 注意,這里的引號需要加
sql = 'insert into star(name, money, province, age, sex) values("%s", "%s", "%s", "%s", "%s")' % (obj['name'], obj['money'], obj['province'], obj['age'], obj['sex'])
'''
# id = 8
# sql = 'delete from star where id=%s' % id
sql = 'update star set name="馬德華" where id=12'
# 注意蜡歹,沒有添加進去屋厘,是因為沒有提交,需要提交才能成功
try:
cursor.execute(sql)
# 提交季稳,寫入磁盤
db.commit()
except Exception as e:
print(e)
# 回滾到最初始的狀態(tài)
db.rollback()
finally:
cursor.close()
db.close()
自己擬寫一個基本的數(shù)據(jù)庫操作類擅这,當(dāng)然之后使用的還是大神們寫的那些比較高級的庫類之類的澈魄。
import pymysql
class MyMysql(object):
def __init__(self, host, port, user, password, db, charset):
self.host = host
self.port = port
self.user = user
self.password = password
self.dbname = db
self.charset = charset
# 鏈接數(shù)據(jù)庫
self.connect()
def connect(self):
# 鏈接數(shù)據(jù)庫和獲取游標
self.db = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password, db=self.dbname, charset=self.charset)
self.cursor = self.db.cursor()
def run(self, sql):
ret = None
try:
ret = self.cursor.execute(sql)
self.db.commit()
except Exception as e:
self.db.rollback()
finally:
self.close()
return ret
def close(self):
self.cursor.close()
self.db.close()
def insert(self, sql):
return self.run(sql)
def update(self, sql):
return self.run(sql)
def delete(self, sql):
return self.run(sql)
def read_one(self, sql):
ret = None
try:
self.cursor.execute(sql)
# 獲取得到數(shù)據(jù)
ret = self.cursor.fetchone()
except Exception as e:
print('查詢失敗')
finally:
self.close()
return ret
def read_many(self, sql):
ret = None
try:
self.cursor.execute(sql)
# 獲取得到數(shù)據(jù)
ret = self.cursor.fetchall()
except Exception as e:
print('查詢失敗')
finally:
self.close()
return ret