目录结构
pip安装pymysql
import pymysql
import pymysql.cursors
import json
import hashlib
def connectdb():
print('连接到mysql服务器...')
# 打开数据库
db = pymysql.connect("localhost", "root", "root", "test")
print('连接上了!')
return db
def closedb(db):
db.close()
print('链接关闭了')
def find(db, sql):
cursor = db.cursor(cursor=pymysql.cursors.DictCursor)
try:
# 执行sql语句
cursor.execute(sql)
results = cursor.fetchall()
print(json.dumps(results))
return results
except:
# Rollback in case there is any error
print('查询数据失败!')
return 'None'
def insertUser(db, table, arr):
index = 0
insertVal = []
insertKeString = ''
cursor = db.cursor()
while index < len(arr):
item = 0
for key in arr[index]:
insertVal.append(str(arr[index][key]).replace("\n", ""))
if item == len(arr[index]) - 1:
insertKeString += '`' + str(key) + '`'
insertVal = tuple(insertVal)
string = '(' + insertKeString + ')'
sqlStr = "INSERT INTO `py_key` " + string + " VALUES " + str(
insertVal) + ';'
print(sqlStr)
cursor.execute(sqlStr)
# 提交到数据库执行
db.commit()
print("遍历完成")
else:
insertKeString += '`' + str(key) + '`' + ', '
print('仍在遍历中' + str(len(arr[index])))
print(item)
item += 1
index += 1
使用
先引入
我这里是保存rsa密匙对
def insertUser(db, table, arr):
db是mysql链接,table是表名,arr是列表嵌套字典,这样就可以像php一样用数组嵌套数组来实现多条插入数据库
con = db.connectdb()
db.insertUser(con, 'py_key', [{'public_pen': PUBLIC_PEM.decode('utf-8'), 'private_pen': PRIVATE_PEM.decode('utf-8'),
'create_time': time.time(), 'ip': ip}])
最后,如果有什么不对的地方,望大侠们指出!