python數(shù)據(jù)庫連接與操作

import pymysql

class OperationMysql:

"""

? ? 數(shù)據(jù)庫SQL相關(guān)操作import pymysql

# 打開數(shù)據(jù)庫連接db = pymysql.connect("localhost","testuser","test123","TESTDB" )

# 使用 cursor() 方法創(chuàng)建一個游標(biāo)對象cursor

cursor = db.cursor()

# 使用 execute()? 方法執(zhí)行 SQL 查詢cursor.execute("SELECT VERSION()")

"""

? ? def __init__(self):

# 創(chuàng)建一個連接數(shù)據(jù)庫的對象

? ? ? ? self.conn = pymysql.connect(

host='00000000',? # 連接的數(shù)據(jù)庫服務(wù)器主機(jī)名

? ? ? ? ? ? port=3306,? # 數(shù)據(jù)庫端口號

? ? ? ? ? ? user='paidan_user',? # 數(shù)據(jù)庫登錄用戶名

? ? ? ? ? ? passwd='aaA5y6C9vL',

? ? ? ? ? ? db='test2',? # 數(shù)據(jù)庫名稱

? ? ? ? ? ? charset='utf8',? # 連接編碼

? ? ? ? ? ? cursorclass=pymysql.cursors.DictCursor

)

# 使用cursor()方法創(chuàng)建一個游標(biāo)對象,用于操作數(shù)據(jù)庫

? ? ? ? self.cur =self.conn.cursor()

# 查詢一條數(shù)據(jù)

? ? def search_one(self, sql):

self.cur.execute(sql)

result =self.cur.fetchone()# 使用 fetchone()方法獲取單條數(shù)據(jù).只顯示一行結(jié)果

? ? ? ? # result = self.cur.fetchall()? # 顯示所有結(jié)果

? ? ? ? return result

# 更新SQL

? ? def updata_one(self, sql):

try:

self.cur.execute(sql)# 執(zhí)行sql

? ? ? ? ? ? self.conn.commit()# 增刪改操作完數(shù)據(jù)庫后,需要執(zhí)行提交操作

? ? ? ? except:

# 發(fā)生錯誤時回滾

? ? ? ? ? ? self.conn.rollback()

self.conn.close()# 記得關(guān)閉數(shù)據(jù)庫連接

? ? # 插入SQL

? ? def insert_one(self, sql):

try:

self.cur.execute(sql)# 執(zhí)行sql

? ? ? ? ? ? self.conn.commit()# 增刪改操作完數(shù)據(jù)庫后,需要執(zhí)行提交操作

? ? ? ? except:

# 發(fā)生錯誤時回滾

? ? ? ? ? ? self.conn.rollback()

self.conn.close()

# 刪除sql

? ? def delete_one(self, sql):

try:

self.cur.execute(sql)# 執(zhí)行sql

? ? ? ? ? ? self.conn.commit()# 增刪改操作完數(shù)據(jù)庫后,需要執(zhí)行提交操作

? ? ? ? except:

# 發(fā)生錯誤時回滾

? ? ? ? ? ? self.conn.rollback()

self.conn.close()

if __name__ =='__main__':

op_mysql = OperationMysql()

res = op_mysql.search_one("SELECT * FROM order_case where id = '612244' ")

print(res)




from test_case.test_2import OperationMysql? ?導(dǎo)入方法

sql=OperationMysql().select_one('select * from? application ')

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容