資料庫操作 pymysql 封裝處理(中級)

2022-07-30 04:06:08 字數 2650 閱讀 2987

**如下:

import

pymysql

from pymysql.cursors import

dictcursor

class

dbhandler(object):

"""初始化資料庫

"""#

也可以繼承 connection 這裡沒有選擇繼承

def__init__

(self,

host=none, #

連線名 port=3306, #

埠 user=none, #

使用者名稱 password=none, #

密碼 charset=none, #

不能寫utf-8 在mysql裡面寫utf-8會報錯

database=none, #

資料庫庫名

cursorclass=dictcursor,

**kwargs):

self.connect =pymysql.connect(

host=host, #

連線名 port=port, #

埠 user=user, #

使用者名稱 password=password, #

密碼 charset=charset, #

不能寫utf-8 在mysql裡面寫utf-8會報錯

database=database, #

資料庫庫名

cursorclass=cursorclass, #

資料轉換成字典格式

**kwargs

)#建立游標物件 **主要**

self.cursor =self.connect.cursor()

def query_one(self, query, args=none):

"""查詢資料庫一條資料

:param query: 執行mysql語句

:param args: 與查詢語句一起傳遞的引數(給語句傳參) 元組、列表和字典

"""self.cursor.execute(query, args)

#將更改提交到資料庫

self.connect.commit()

return

self.cursor.fetchone()

def query_all(self, query, args=none):

"""查詢資料庫所有資料

:param query: 執行mysql語句

:param args: 與查詢語句一起傳遞的引數(給語句傳參) 元組、列表和字典

"""self.cursor.execute(query, args)

#將更改提交到資料庫

self.connect.commit()

return

self.cursor.fetchall()

def query(self, query, args=none, one=true):

"""主體查詢資料

:param query: 執行mysql語句

:param args: 與查詢語句一起傳遞的引數(給語句傳參) 元組、列表和字典

:param one: one是true 時候執行query_one, 否則執行query_all

"""if

one:

return

self.query_one(query, args)

return

self.query_all(query, args)

defclose(self):

"""關閉

:return:

"""#

關閉游標

self.cursor.close()

#斷開資料庫連線

self.connect.close()

if__name__ == '

__main__':

db =dbhandler(

host='

127.0.0.1

', #

連線名 port=3306, #

埠 user='

root

', #

使用者名稱 password='

root

', #

密碼 charset='

utf8

', #

不能寫utf-8 在mysql裡面寫utf-8會報錯

database='

pymysql_test'#

資料庫庫名

)

# 查詢語句

sql = '

select * from authors

'sql1 = "

select * from authors where authorid = %s;

"print(db.query(sql, one=false))

print(db.query(query=sql1, args=[1]))

# 關閉連線

db.close()

pymysql 資料庫操作

參考文件 import pymysql dbparams conn pymysql.connect dbparams cursor conn.cursor sql select sname,sclass from student try cursor.execute sql 獲取查詢結果 data ...

python操作pymysql資料庫

首先需要匯入通過import pymysql匯入資料庫模組 已經建立好乙個資料庫test,資料庫中有乙個空表t,只有兩個欄位id int 5 name varchar 20 import pymysql conn pymysql.connect host 127.0.0.1 port 3306,us...

使用PyMySQL操作mysql資料庫

使用pymysql操作mysql資料庫 python版本 2.6或3.3 mysql版本 4.1 使用pip安裝,在命令列執行如下命令 1 pip install pymysql 其中的x.x是版本 目前可以獲取的最新版本是0.6.6 1 python setup.py install 建議使用pi...