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("连接数据库....")
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("连接数据库成功")
def disConnectDB(self):
print("关闭库连接....")
# 关闭游标
self.cursor.close()
# 提交事务
self.conn.commit()
# 关闭数据库连接
self.conn.close()
print("数据库连接已关闭!")
def execute_sql(self,sql):
self.connectDB()
if sql[:6]=="select":
"""查询select """
self.cursor.execute(sql)
datas = self.cursor.fetchall()
print("共%s条数据。" %len(datas))
elif sql[:6]=="insert":
datas=self.cursor.execute(sql)
print("插入语句受影响的行数:", datas)
elif sql[:6]=="update":
datas=self.cursor.execute(sql)
print("修改语句受影响的行数:", datas)
elif sql[:6]=="delete":
datas=self.cursor.execute(sql)
print("删除语句受影响的行数: ",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))