python資料庫封裝的辦法

2021-08-21 11:00:28 字數 1880 閱讀 3160

#

匯入pymysql

框架,可以用

pipimport pymysql

#資料庫封裝方法

class mysqlhelp(object):

config=

def

__init__(self):

self.connection=none

self.cursor=none

#該函式用來從資料庫表中查詢一行資料

def

getone(self

,sql,*args):

try:

self.connection = pymysql.connect(**mysqlhelp.config)

self.cursor=self.connection.cursor()

self.cursor.execute(sql,args)

return

self.cursor.fetchone()

except

exception

as ex:

print(ex,ex)

finally:

self.close()

def

close(self):

if(self.cursor):

self.cursor.close()

if(self.connection):

self.connection.close()

#該函式用來從資料庫表中查詢多行資料

def

getlist(self

,sql,*args):

try:

self.connection = pymysql.connect(**mysqlhelp.config)

self.cursor=self.connection.cursor()

self.cursor.execute(sql,args)

return

self.cursor.fetchall()

except

exception

as ex:

print(ex,ex)

finally:

self.close()

# 該函式用來從資料庫表中查詢多行資料

def

executedml(self

, sql, *args):

try:

self.connection = pymysql.connect(**mysqlhelp.config)

self.cursor = self.connection.cursor()

#返回sql

語句執行以後影響的行數

num = self.cursor.execute(sql, args)

self.connection.commit()

return num

except

exception

as ex:

self.connection.rollback()

print(ex, ex)

finally:

self.close()

def

close(self):

if(self.cursor):

self.cursor.close()

if(self.connection):

self.connection.close()

if __name__=='__main__':

helper=mysqlhelp()

#輸入操作內容

print(helper.executedml('delete from t_student where id=%d'%6))

python 資料庫的封裝

coding utf 8 import os import sqlite3 defjudge sql sql 判斷sql型別 sql sql.strip lower ret fetch if sql.startswith select select pass elif sql.startswith ...

十四 python資料庫的封裝

import pymysql 查 所資料 defget all sql conn pymysql.connect host localhost user root password root database db6 cur conn.cursor cursor pymysql.cursors.di...

python 對ACCESS資料庫操作封裝模組

coding utf 8 by adengou 2016 01 02 programe python3.4.4 import os import json import win32com.client access資料模組 class access model def init self,datau...