博客
关于我
Python 操作sqlite数据库及保存查询numpy类型数据(二)
阅读量:798 次
发布时间: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 virtualenv
    查看>>
    python vue3实现大文件分段续传(断点续传)--带暂停和继续功能
    查看>>
    Python WebDriver如何打印整个页面源(html)
    查看>>
    Python WebSocket自动化测试:构建高效接口测试框架
    查看>>
    Python Web开发
    查看>>
    Redis 配置文件杂项。
    查看>>
    Python web自动化测试 —— 文件上传
    查看>>
    Python web自动化测试 —— 文件上传!
    查看>>
    Python Web自动化测试开发环境搭建(附安装包与虚拟机环境)
    查看>>
    python win32api键盘_Python win32api.keybd_event模拟键盘输入
    查看>>
    python Windows显示当前鼠标坐标
    查看>>
    python Workbook 表格宽度
    查看>>
    python | flanker,一个神奇的 Python 库!
    查看>>
    python | flower,一个强大的 Python 库!
    查看>>
    python | funcy,一个超强的 提供函数式编程工具 Python 库!
    查看>>
    python | ggplot,一个超强的 Python 库!
    查看>>
    python | grab,一个强大的 Python 库!
    查看>>
    python | h5py,一个无敌的关于 HDF5 的 Python 库!
    查看>>
    python | huey,一个非常厉害的 任务调度 Python 库!
    查看>>
    python | hypothesis,一个有趣的 Python 库!
    查看>>