import numpy as np
import pymysql
def insertData(numpy_bytes,shape_str):
db = pymysql.connect(host="localhost", user="root", password="19950127", db="test", port=3306)
#连接数据库对象
cur = db.cursor()
#游标对象
sql = "insert into face_data(numpy_data,shape) values(%s,%s)"
#定义好sql语句,%s是字符串的占位符
try:
cur.execute(sql,(numpy_bytes,shape_str))
#执行sql语句
db.commit()
#提交到数据库中
except Exception as e:
#捕获异常
raise e
finally:
db.close() # 关闭连接
def upData(numpy_bytes,shape_str):
db = pymysql.connect(host="localhost", user="root", password="19950127", db="test", port=3306)
#连接数据库对象
# 使用cursor()方法获取操作游标
cur = db.cursor()
sql_update1 ="update face_data set numpy_data = %s where id = %d"
sql_update2 ="update face_data set shape = %s where id = %d"
try:
cur.execute(sql_update2 % (shape_str,12)) #像sql语句传递参数
cur.execute(sql_update1 % (numpy_bytes,12)) #像sql语句传递参数
#提交
db.commit()
except Exception as e:
#错误回滚
db.rollback()
finally:
db.close()
def readData():
db = pymysql.connect(host="localhost", user="root", password="19950127", db="test", port=3306)
#连接数据库对象
cur = db.cursor()
#游标对象
sql = "select * from face_data"
#定义好sql语句,%s是字符串的占位符
try:
cur.execute(sql)
#执行sql语句
results = cur.fetchall()
#获取所有结果集
for row in results:
numArr = np.fromstring(string=row[1], dtype=int)
#将读取到的字节流转化为ndarray数组
shape = tuple(eval(row[2]))
#将读取到的shape转换为元组的格式,这里的eval(),由于我们元组里面的数据是int的所以,这里eval()的作用就是把本该是数字的转化回来
numArr.shape = shape
#设置维度,设置的数值为元组
print(numArr)
db.commit()
#提交到数据库中
except Exception as e:
#捕获异常
raise e
finally:
db.close() # 关闭连接
if __name__ == '__main__':
arr =np.arange(5, 50).reshape(3,5,3)
#生产0-45数字的维度=(3,5,3)的三维数组
shape_ = arr.shape
#获取数组的维度
numpy_bytes = arr.tostring()
#将数组转化为二进制流
shape_str = "".join(str(shape_))
#将shape元组转化为字符串
#insertData(numpy_bytes, shape_str)
#插入数据库
upData(numpy_bytes, shape_str)
#更新数据库
readData()
#读取数据库
老师您好,我想尝试着储存np数组。将数组转化为bytes格式的二进制流后,在插入和读取部分都没有问题,但是在更新数据库时遇到了很大的问题,是占位符不对吗?您能帮我看下吗,麻烦了!