新建類封裝數(shù)據(jù)庫增刪改查封裝若干個方法

import pymysql

class DATABASE:

? ? def __init__(self,host,port,user,passwd,db,charset="utf8"):

? ? ? ? self.host=host

? ? ? ? self.port=port

? ? ? ? self.user=user

? ? ? ? self.passwd=passwd

? ? ? ? self.db=db

? ? ? ? self.charset=charset



#self.conn=pymysql.connect(host=self.host,port=self.port,user=self.user,passwd=self.passwd,db=self.db,charset=self.charset)

? ? ? ? #self.cursor=self.conn.cursor()

? ? def connectDB(self):

? ? ? ? print("連接數(shù)據(jù)庫....")



self.conn=pymysql.connect(host=self.host,port=self.port,user=self.user,passwd=self.passwd,db=self.db,charset=self.charset)

? ? ? ? self.cursor=self.conn.cursor()

? ? ? ? print("連接數(shù)據(jù)庫成功")

? ? def disConnectDB(self):

? ? ? ? print("關閉庫連接....")

? ? ? ? # 關閉游標

? ? ? ? self.cursor.close()

? ? ? ? # 提交事務

? ? ? ? self.conn.commit()

? ? ? ? # 關閉數(shù)據(jù)庫連接

? ? ? ? self.conn.close()

? ? ? ? print("數(shù)據(jù)庫連接已關閉!")

? ? def execute_sql(self,sql):

? ? ? ? self.connectDB()

? ? ? ? if sql[:6]=="select":

? ? ? ? ? ? """查詢select """

? ? ? ? ? ? self.cursor.execute(sql)

? ? ? ? ? ? datas = self.cursor.fetchall()

? ? ? ? ? ? print("共%s條數(shù)據(jù)。" %len(datas))

? ? ? ? elif sql[:6]=="insert":

? ? ? ? ? ? datas=self.cursor.execute(sql)

? ? ? ? ? ? print("插入語句受影響的行數(shù):", datas)

? ? ? ? elif sql[:6]=="update":

? ? ? ? ? ? datas=self.cursor.execute(sql)

? ? ? ? ? ? print("修改語句受影響的行數(shù):", datas)

? ? ? ? elif sql[:6]=="delete":

? ? ? ? ? ? datas=self.cursor.execute(sql)

? ? ? ? ? ? print("刪除語句受影響的行數(shù): ",datas)

? ? ? ? else:

? ? ? ? ? ? datas=None

? ? ? ? self.disConnectDB()

? ? ? ? return datas

if __name__=="__main__":

? ? db=DATABASE("192.168.202.133",3306,"root","123123","grdb","utf8")

? ? sql_select="select * from user "

? ? print(db.execute_sql(sql_select))

sql_insert="insert into user values(555,'tom555','tom555','1989-03-17')"

? ? print(db.execute_sql(sql_insert))

sql_update="update user set birthday='2100-08-12' where name='lucy0'"

? ? print(db.execute_sql(sql_update))

? ? sql_delete="delete from user where name='lucy1'"

? ? print(db.execute_sql(sql_delete))

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 1.數(shù)據(jù)庫簡介 人類在進化的過程中,創(chuàng)造了數(shù)字、文字、符號等來進行數(shù)據(jù)的記錄,但是承受著認知能力和創(chuàng)造能力的提升,...
    大熊_7d48閱讀 605評論 0 1
  • 1、安裝mysql模塊 python2 ubuntu16.4環(huán)境下安裝 先安裝依賴,否則安裝mysql-pytho...
    郭強成就閱讀 230評論 0 1
  • import MySQLdb class MysqlSearch(object): def __init__(se...
    hearys閱讀 1,215評論 0 0
  • 數(shù)據(jù)庫編程概述、pymysql基本操作方法總結、參數(shù)化列表防止SQL注入總結 2.6 Python數(shù)據(jù)庫編程 學習...
    Cestine閱讀 1,837評論 0 2
  • 一、Python簡介和環(huán)境搭建以及pip的安裝 4課時實驗課主要內容 【Python簡介】: Python 是一個...
    _小老虎_閱讀 6,323評論 0 10

友情鏈接更多精彩內容