python操作mysql数据库

2018-11-05 08:25:03来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

先简单写一个操作mysql数据库类,后面再改进

# -*- coding:utf-8 -*-
import pymysql

class SunckSql():
def __init__(self,host,user,password,database,port):
self.host=host
self.user=user
self.passwd=password
self.dbName=database
self.port=port

def connect(self):
self.db = pymysql.connect(self.host,self.user,self.passwd,self.dbName,self.port)
self.cursor=self.db.cursor()

def close(self):
self.cursor.close()
self.db.close()

def get_one(self,sql):
res=None
try:
self.connect()
self.cursor.execute(sql)
res=self.cursor.fetchone()
except Exception as e:
print(e)
print("查询失败")
finally:
self.close()
return res

def get_all(self,sql):
res=()
try:
self.connect()
self.cursor.execute(sql)
res=self.cursor.fetchall()
except Exception as e:
print(e)
print("查询失败")
finally:
self.close()
return res

def insert(self,sql):
count=0
try:
self.connect()
count=self.cursor.execute(sql)
print("插入数据成功")
self.db.commit()
except Exception as e:
print(e)
print("插入数据失败")
self.db.rollback()
finally:
self.close()
return count

def update(self,sql):
count = 0
try:
self.connect()
count = self.cursor.execute(sql)
print("数据更新成功")
self.db.commit()
except Exception as e:
print(e)
print("数据更新失败")
self.db.rollback()
finally:
self.close()
return count

def delete(self,sql):
count = 0
try:
self.connect()
count = self.cursor.execute(sql)
print("删除数据成功")
self.db.commit()
except Exception as e:
print(e)
print("数据删除失败")
self.db.rollback()
finally:
self.close()
return count

if __name__ == '__main__':
s = SunckSql(host="xxx", user='xxx', password='xxx', database='xx', port=xx)
# res = s.get_all("select * from ce")
# for row in res:
# print("%d----%s" % (row[0], row[1]))
# s.delete("delete from ceshi where id=10")
# s.insert("insert into bk values (3,'bk')")
# t=s.get_one("select * from bk where id=15")
# print(t)
# s.update("update bk set name='hg1' where id=3")
s.delete("delete from bk where id=3")

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:python3 正则表达式点星问号(.*?)能不能匹配换行符?不能的话应

下一篇:Python & 机器学习之项目实践