-
Notifications
You must be signed in to change notification settings - Fork 67
/
data_to_mysql.py
78 lines (69 loc) · 2.13 KB
/
data_to_mysql.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
69
70
71
72
73
74
75
76
77
78
'''
@author:KongWeiKun
@file: data_to_mysql.py
@time: 18-1-20 下午1:44
@contact: 836242657@qq.com
'''
import pymysql
# import setting
import time
import logger
class Mysql:
host = 'localhost'
user = 'root'
pwd = 'Hanhuan.0214'
db = 'wangyi'
#获取当前时间
def getCurrentTime(self):
return time.strftime('[%Y-%m-%d %H:%M:%S]',time.localtime(time.time()))
#数据库初始化
def __init__(self):
try:
self.con = pymysql.connect(self.host,
self.user,
self.pwd,
self.db,
use_unicode=True, charset="utf8")
self.con.autocommit(True)
self.cursor = self.con.cursor()
except pymysql.Error as e :
print('错误')
#入库
def insertData(self,table,my_dict):
try:
cols = ','.join(my_dict.keys())
values = '","'.join(my_dict.values())
sql = "insert into %s (%s) values (%s)"%(table,cols,'"'+values+'"')
try:
result = self.cursor.execute(sql)
insert_id = self.con.insert_id()
#判断成功
if result:
return insert_id
else:
return 0
except pymysql.Error as e:
# 发生错误时回滚
self.con.rollback()
# 主键唯一,无法插入
if "key 'PRIMARY'" in e.args[1]:
print('数据已存在')
else:
print('数据已存在,未插入数据%s',str(my_dict))
return -1
except pymysql.Error as e:
print('链接错误')
return -1
if __name__ == '__main__':
d = Mysql()
commentData = {
'id': '1',
'user': '1',
'content': '你好',
'likecount': '1'
}
# cols = ', '.join(commentData.keys())
# print(cols)
values = '","'.join(commentData.values())
print(values)
# d.insertData('comments', commentData)