您好,登錄后才能下訂單哦!
這篇文章主要介紹了pymysql如何封裝,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
示例
#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如何封裝”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。