numpy数组之存取数据库

前言:

该项目环境为Ubuntu16.04,python3.5

python库为pymysql,安装直接在终端输入pip3 install pymysql

使用参考:https://blog.csdn.net/qq_37176126/article/details/72824106

数据库采用mysql,附上安装链接:https://blog.csdn.net/nancy50/article/details/81080693

mysql的可视化操作软件是navicat,附上安装链接:https://blog.csdn.net/superit401/article/details/78110079/

 

这是数据库表的结构

 

存储数据后

 

以下是具体实现代码,实现numpy数组存入数据库,从数据库读取


import  numpy as np
import pymysql as ml

def insertData(numpy_bytes,shape_str):
    db = ml.connect(host="localhost", user="root", password="123456", 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 readData():
    db = ml.connect(host="localhost", user="root", password="123456", 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(0, 45).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)
    #插入数据库
    readData()
    #读取数据库

猜你喜欢

转载自blog.csdn.net/Chen_RuiMin/article/details/86532699