博客
关于我
Python 操作sqlite数据库及保存查询numpy类型数据(二)
阅读量:796 次
发布时间:2023-03-07

本文共 925 字,大约阅读时间需要 3 分钟。

为了将numpy数组存储到SQLite数据库并读取出来,可以按照以下步骤进行操作:

  • 安装必要的库

    • 确保已经安装了numpysqlite3库。
    • 在终端中输入以下命令:
      pip install numpy sqlite3
  • 创建内存数据库

    • 使用以下命令创建一个内存数据库:
      import sqlite3conn = sqlite3.connect(':memory:', isolation_level=None)cursor = conn.cursor()
  • 创建数据库表

    • 执行以下命令创建一个名为test2的表,字段arr使用BLOB类型来存储二维数组:
      cursor.execute("create table test2 (arr BLOB)")
  • 将numpy数组存储到数据库

    • 创建一个二维numpy数组:
      x = np.arange(12).reshape(2, 6)
    • 使用json.dumps()将numpy数组转换为JSON字符串并插入表中:
      cursor.execute("insert into test2 (arr) values (?)", (json.dumps(x.tolist()),))conn.commit()
  • 读取数据

    • 从数据库中读取arr字段的值:
      cursor.execute("select arr from test2")data = cursor.fetchall()
    • 打印读取到的数据和数据类型:
      print(data)print(type(data))
  • 将读取到的数据转换为numpy数组

    • 使用json.loads()将JSON字符串转换为列表,然后再将其转换为numpy数组:
      my_list = json.loads(data[0][0])temp = np.array(my_list)print(temp)print(type(temp))
  • 关闭数据库连接

    • 关闭数据库cursor和连接:
      cursor.close()conn.close()
  • 通过以上步骤,可以成功地将numpy数组存储到SQLite数据库,并在需要时读取和转换回来。确保在处理数据库时注意异常处理,以避免潜在的错误。

    转载地址:http://vvofk.baihongyu.com/

    你可能感兴趣的文章
    python os文件/目录
    查看>>
    Python Package 之 Faker(随机姓名、电话)
    查看>>
    python pandas TimeStamps到夏令时的本地时间字符串
    查看>>
    Python Pandas 用顶行替换标题
    查看>>
    Python Pandas-从DataFrame按类别绘制多个条形图
    查看>>
    Python PyQt5 将不再显示此消息复选框添加到 QMessageBox
    查看>>
    Python PyQt5:如何使用 PyQt5 显示错误消息
    查看>>
    Python pytest 面试题!
    查看>>
    Python pytz 时区函数返回一个相差 9 分钟的时区
    查看>>
    python rabbitmq实现简单/持久/广播/组播/topic/rpc消息异步发送可配置Django
    查看>>
    Python random和json模块
    查看>>
    Python random模块seed理解
    查看>>
    python range()函数
    查看>>
    Python rdflib可传递查询
    查看>>
    python redis 集群_python 搭建redis集群
    查看>>
    python redis连接,在Python中使用Redis连接池的正确方法
    查看>>
    python regex_Python RegEx
    查看>>
    python requests post 中文结果请求得到unicode
    查看>>
    Python Requests接口自动化测试实战
    查看>>
    Python requests模块
    查看>>