-
Notifications
You must be signed in to change notification settings - Fork 0
/
MysqlHelper.py
68 lines (54 loc) · 1.43 KB
/
MysqlHelper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# -*- coding: utf-8 -*-
import MySQLdb
import conf
def connect():
try:
cxn = MySQLdb.connect(host=conf.HOST, user=conf.USER, passwd=conf.PASSWORD,port=conf.PORT,db=conf.DBNAME,charset=conf.CHARSET)
return cxn
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
# 插入操作
def insert_one(cur,sql,value):
res = cur.execute(sql,value)
# 插入成功,res 返回值为1
if 1 != res:
print 'failed'
else:
print 'success'
def insert_many(cur,sql,values):
res = cur.executemany(sql ,values)
# 插入成功,res 返回值为1
if 1 != res:
print 'failed'
else:
print 'success'
getRC = lambda cur: cur.rowcount if hasattr(cur,'rowcount') else -1
# 更新操作
def update(cur,sql,params):
cur.execute(sql,params)
return getRC(cur)
# 删除操作
def delete(cur,sql,params):
cur.execute(sql,params)
return getRC(cur)
# 只获取一条记录,返回的是一个元组
def fetch_one(cur,sql):
count = cur.execute(sql)
#print count
result = cur.fetchone();
return result
# 获取多条数据;返回的是二维元组;
def fetch_all(cur,sql):
count = cur.execute(sql)
#print count
results = cur.fetchall();
'''
print results
for r in results:
print r
'''
return results
# 提交的完成操作
def finish(cxn):
cxn.commit()
cxn.close()