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