验证中...
本周日【珠海源创会】一起聊聊:PingCAP分布式事务、支付宝移动端实践、GSBN技术框架选型,点此报名占座
语言: Python
分类: 常用工具包
最后更新于 2018-06-10 22:11
db = Db('127.0.0.1', 3306, 'root', 'pwd', 'db') db.select('select * from t_course')
原始数据 复制代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
from logger import Logger
# 获取logger实例
logger = Logger().get_logger()
# 定义类
class Db:
conn = None
# 构造函数
def __init__(self, host, port, user, password, database):
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
# 连接数据库
def get_connect(self):
return pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password, database=self.database)
# 查询
def select(self, sql):
Db.conn = self.get_connect()
cursor = Db.conn.cursor()
cursor.execute(sql)
rows = cursor.fetchall()
cursor.close()
Db.conn.close()
logger.info('results is %s ', rows)
return rows
# 添加
def insert(self, sql):
Db.conn = self.get_connect()
try:
cursor = Db.conn.cursor()
cursor.execute(sql)
Db.conn.commit()
except BaseException:
logger.info('error method for insert, sql is %s ', sql)
# 如果发生错误则回滚
Db.conn.rollback()
raise BaseException('error method for insert')
# 关闭连接
Db.conn.close()
if __name__ == '__main__':
print('main stat......')
db = Db('127.0.0.1', 3306, 'root', 'pwd', 'db')
db.select('select * from t_course')
# db.insert('insert into t_course (course_id, title, total_number) values (1, "test", 1)')

评论列表( 0 )

你可以在登录后,发表评论

搜索帮助

12_float_left_people 12_float_left_close