對pymysql的簡單封裝

2022-03-02 22:54:18 字數 2240 閱讀 2968

#coding=utf-8 

#!/usr/bin/python

import pymysql

class mysql:

"""對pymysql的簡單封裝

"""def __init__(self,host,user,pwd,db):

self.host = host

self.user = user

self.pwd = pwd

self.db = db

def __getconnect(self):

"""得到連線資訊

返回: conn.cursor()

"""if not self.db:

raise(nameerror,"沒有設定資料庫資訊")

self.conn = pymysql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")

cur = self.conn.cursor()

if not cur:

raise(nameerror,"連線資料庫失敗")

else:

return cur

def execquery(self,sql):

"""執行查詢語句

返回的是乙個包含tuple的list,list的元素是記錄行,tuple的元素是每行記錄的字段

呼叫示例:

ms = mysql(host="localhost",user="sa",pwd="123456",db="pythonweibostatistics")

reslist = ms.execquery("select id,nickname from weibouser")

for (id,nickname) in reslist:

print str(id),nickname

"""cur = self.__getconnect()

cur.execute(sql)

reslist = cur.fetchall()

#查詢完畢後必須關閉連線

self.conn.close()

return reslist

def execnonquery(self,sql):

"""執行非查詢語句

呼叫示例:

cur = self.__getconnect()

cur.execute(sql)

self.conn.commit()

self.conn.close()

"""cur = self.__getconnect()

cur.execute(sql)

self.conn.commit()

self.conn.close()

def main():

mysql = mysql(host="192.168.163.36",user="wisdomhr",pwd="wisdomhr",db="wisdomhr")

reslist = mysql.execquery("select city from res_school")

for inst in reslist:

print(inst)

if __name__ == '__main__':

main()

用法如下:

#!/usr/bin/python

#version 3.4

import wispymysql

mysql = wispymysql.mysql(host="192.168.163.36",user="wisdomhr",pwd="wisdomhr",db="wisdomhr")

selectsql = "select id, city from res_school where city like '%\r\n%'"

result = mysql.execquery(selectsql)

for (dbid, city) in result:

rightcity = city.replace('\r\n','')

updatesql= "update res_school set city = '" + rightcity + "' where id = " + str(dbid)

print(updatesql)

mysql.execnonquery(updatesql)

pymysql 封裝呼叫

import pymysql class skq def init self config 建立連線 self.connection pymysql.connect config def add self,dict,table 執行sql語句 try with self.connection.cur...

pymysql語法 pymysql庫常用物件用法

pymysql庫中提供了兩個常用的物件 connection物件和cursor物件。1.connection物件 connection物件用於建立與mysql資料庫的連線,可以通過以下方法建立 connect 引數列表 以上方法中的常用引數及其含義如下 引數host,資料庫所在主機的ip主機位址,若...

python 封裝pymysql的思路步驟

目標 封裝乙個模組 功能,呼叫模組,可以快捷的操作pymysql 的相關功能 分析 pymysql並不是一匯入就可以用的 使用之前要做一些事情 考慮 把使用前必做的事情,放到初始化的init方法中 更進一步 pymysql在使用之前,得先 1,連線mysql,獲得連線物件 2,通過連線物件,獲得游標...