方法和類 封裝python資料庫

2021-10-22 10:10:19 字數 3264 閱讀 6396

import pymysql

#用於查詢乙個資料

defget_one

(sql,args)

: conn = pymysql.connect(host=

"localhost"

, user=

"root"

, password=

"1234567"

, database=

"python_db"

,charset=

'utf8'

) cursor = conn.cursor(cursor=pymysql.cursors.dictcursor)

cursor.execute(sql,args)

result = cursor.fetchone(

) cursor.close(

) conn.close(

)return result

#用於查詢多個資料

defget_list

(sql,args)

: conn = pymysql.connect(host=

"localhost"

, user=

"root"

, password=

"1234567"

, database=

"python_db"

,charset=

'utf8'

) cursor = conn.cursor(cursor=pymysql.cursors.dictcursor)

cursor.execute(sql,args)

result = cursor.fetchall(

) cursor.close(

) conn.close(

)return result

#用於增刪改

defmodify

(sql,args)

: conn = pymysql.connect(host=

"localhost"

, user=

'root'

, password=

'1234567'

, database=

'python_db'

, charset=

'utf8'

) cursor = conn.cursor(cursor=pymysql.cursors.dictcursor)

cursor.execute(sql,args)

conn.commit(

) cursor.close(

) conn.close(

)#具有返回值

defcreate

(sql,args)

: conn = pymysql.connect(host=

"localhost"

, user=

'root'

, password=

'1234567'

, database=

'python_db'

, charset=

'utf8'

) cursor = conn.cursor(cursor=pymysql.cursors.dictcursor)

cursor.execute(sql, args)

conn.commit(

)#lastrowid 獲得最後插入記錄後取得主鍵id的方法

last_row_id=cursor.lastrowid

cursor.close(

) conn.close(

)return

#建立類防止乙個方法在插入多條資料時反覆的開啟和關閉資料庫

class

sql(

object):

#開啟資料庫

defconnect

(self)

: self.conn=pymysql.connect(host=

"localhost"

, user=

'root'

, password=

'1234567'

, database=

'python_db'

, charset=

'utf8'

) self.cursor= self.conn.cursor(cursor=pymysql.cursors.dictcursor)

defget_list

(self,sql,args)

: self.cursor.execute(sql, args)

result = self.cursor.fetchall(

)return result

defget_one

(self,sql,arg)

: self.cursor.execute(sql, arg)

result = self.cursor.fetchone(

)return result

defmodify

(self,sql,args)

: self.cursor.execute(sql, args)

self.conn.commit(

)# 新增並且拿返回值

defcreate

(self,sql,args)

: self.cursor.execute(sql, args)

self.conn.commit(

)# lastrowid 獲得最後插入記錄後取得主鍵id的方法

last_row_id = self.cursor.lastrowid

return last_row_id

#進行對組資料的修改

defmultiple_motify

(self,sql,args)

:#self.cursor.executmany('insert into student(id,name) values(%s,%s)',[(1,'ax'),(2,'ss')])

self.cursor.executemany(sql,args)

self.conn.commit(

)def

close

(self)

: self.cursor.close(

) self.conn.close(

)

C 封裝資料庫類

using system using system.collections.generic using system.text using system.data using system.configuration using system.web using system.web.securit...

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 ...

php連線資料庫封裝類,php 資料庫的封裝類

php 資料庫的封裝類 class db private link function connectdb dbhost,dbuser,dbpw,dbname pconnect 1 if pconnect if this link mysql pconnect dbhost,dbuser,dbpw t...