# -*- coding:utf-8 -*-
import MySQLdb
import time
'''
· MySQL 操作类
· V1.0
'''
class MySQLClass(object):
def __init__(self, host, user, password, charset="utf8"):
super(MySQLClass, self).__init__()
self.host = host
self.user = user
self.password = password
self.port = 3307
self.charset = charset
try:
self.conn = MySQLdb.connect(host=self.host, user=self.user, passwd=self.password, port=self.port)
self.conn.set_character_set(self.charset)
self.cur = self.conn.cursor()
except MySQLdb.Error as e:
self.printError(e, '')
def getTime(self):
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
def printError(self, e, sql):
print("{0} MySQl Error {1}: {2}".format(self.getTime(), e.args[0], e.args[1]))
print(sql)
def setdb(self, db):
try:
self.conn.select_db(db)
except MySQLdb.Error as e:
self.printError(e, '')
# 新增
def insert(self, tablename, DicData):
try:
arrParam = []
arrValue = []
for key in DicData:
arrParam.append('%s')
arrValue.append(DicData[key])
strfield = '`{0}`'.format('`,`'.join(DicData.keys()))
strParam = 'values({0})'.format(','.join(arrParam))
sql = 'insert into {0}({1}) {2};'.format(tablename, strfield, strParam)
self.cur.execute(sql, tuple(arrValue)) # 单调新增
self.conn.commit()
except MySQLdb.Error as e:
self.printError(e, sql)
# self.conn.close()
# 批量新增
def insertBatch(self, tablename, arrFiled, arrTupleValue):
try:
strfield = '`{0}`'.format('`,`'.join(arrFiled))
arrParam = []
for x in arrFiled:
arrParam.append('%s')
strParam = 'values({0})'.format(','.join(arrParam))
sql = 'insert into {0}({1}) {2};'.format(tablename, strfield, strParam)
self.cur.executemany(sql, tuple(arrTupleValue)) # many 多条新增
self.conn.commit()
except MySQLdb.Error as e:
self.printError(e, '')
# self.conn.close()
# 更新语句
def update(self, sql):
try:
self.cur.execute(sql)
self.conn.commit()
except MySQLdb.Error as e:
self.conn.rollback()
self.printError(e, sql)
# self.conn.close()
# 查询单个字段 返回List
def executeList(self, sql):
try:
result = []
self.cur.execute(sql)
ds = self.cur.fetchall()
for i, row in enumerate(ds):
result.append(str(row[0]))
return result
except MySQLdb.Error as e:
self.printError(e, sql)
def executeDataRow(self, sql):
try:
self.cur.execute(sql)
ds = self.cur.fetchall()
return ds
except MySQLdb.Error as e:
self.printError(e, sql)
# db=MySQLClass('127.0.0.1','root','123456')
# db.setdb('test')
# arr=db.executeList('SELECT DISTINCT skuid from commodity')
# for x in arr:
# print(x)
# table=db.insert('commodity',{'title':'10'})
# db.conn.commit()
# arrTr={'title':'1'}
# if 'titl1e' in arrTr:
# print (1)
# else:
# print (0)
# arrFiled = ['name', 'age']
# arrValue=['1','2']
# arrValueS=[]
# arrValueS.append(tuple([1,'1']) )
# arrValueS.append(tuple(['2',2]) )
# arrValueS.append(tuple([3,3]) )
# arrValueS.append(arrValue)
# tuple1=(('2','3'),)
# db.insertBatch('test',arrFiled,arrValueS)
Python MySQL 操作类(有使用例子)
需积分: 50 195 浏览量
2017-03-08
21:34:10
上传
评论 5
收藏 1KB RAR 举报
Howfar丶
- 粉丝: 2
- 资源: 4
最新资源
- python-leetcode面试题解之第157题用Read4读取N个字符-题解.zip
- python-leetcode面试题解之第156题上下翻转二叉树-题解.zip
- python-leetcode面试题解之第155题最小栈-题解.zip
- python-leetcode面试题解之第153题寻找旋转排序数组中的最小值-题解.zip
- python-leetcode面试题解之第152题乘积最大子数组-题解.zip
- python-leetcode面试题解之第151题反转字符串中的单词-题解.zip
- python-leetcode面试题解之第150题逆波兰表达式求值-题解.zip
- python-leetcode面试题解之第149题直线上最多的点数-题解.zip
- python-leetcode面试题解之第148题排序链表-题解.zip
- python-leetcode面试题解之第147题对链表进行插入排序-题解.zip
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈