博客
关于我
Python numpy插入、读取至postgreSQL数据库中bytea类型字段
阅读量:800 次
发布时间:2023-03-06

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

安装psycopg2模块并操作PostgreSQL数据库

安装psycopg2模块

要使用PostgreSQL数据库,可以通过以下命令安装psycopg2模块:

pip install psycopg2

安装完成后,可以按照以下步骤进行数据库操作。


插入数据到数据库

以下函数insertOperate用于将数据插入到数据库中。

def insertOperate():    # 连接数据库    conn = psycopg2.connect(        database="openfire",        user="postgres",        password="postgres",        host="192.168.3.202",        port="5432"    )    cursor = conn.cursor()        # 创建一个二维数组    x = np.arange(12).reshape(2, 6)        # 创建表单    cursor.execute('CREATE TABLE insightface.t_test ("data" bytea)')        # 准备插入数据的SQL语句    insert_sql = "INSERT INTO insightface.t_test (\"data\") VALUES (%s)"    insert_data = json.dumps(x.tolist())    insert_sql = insert_sql % insert_data        # 执行插入操作    cursor.execute(insert_sql)    conn.commit()        # 关闭数据库资源    cursor.close()    conn.close()

运行以上函数后,数据会被插入到insightface.t_test表中。插入的数据格式为:

[[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]]

查询数据库数据

以下函数selectOperate用于从数据库中查询数据并进行处理。

def selectOperate():    # 连接数据库    conn = psycopg2.connect(        database="openfire",        user="postgres",        password="postgres",        host="192.168.3.202",        port="5432"    )    cursor = conn.cursor()        # 查询数据    cursor.execute("SELECT data FROM insightface.t_test")    rows = cursor.fetchall()        for row in rows:        print("获取到的数据:", row[0])        print("数据类型:", type(row[0]))        # 解码数据        data_str = bytes.decode(bytes(row[0]))        print("解码后的字符串:", data_str)        # 将字符串转换为numpy数组        temp = np.array(json.loads(data_str))        print("numpy数组的类型:", type(temp))        print("数组的形状:", temp.shape)        print("数组内容:", temp)        # 关闭数据库资源    cursor.close()    conn.close()

使用说明

  • 安装psycopg2:使用pip install psycopg2命令安装模块。
  • 连接数据库:确保数据库名称、用户名、密码、主机地址和端口正确。
  • 创建表单:使用CREATE TABLE语句创建表单。
  • 插入数据:使用INSERT INTO语句将数据插入数据库。
  • 查询数据:使用SELECT语句查询数据,并对返回结果进行处理。
  • 通过以上步骤,可以方便地与PostgreSQL数据库进行交互。

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

    你可能感兴趣的文章
    Python - 如何使用管道执行shell命令,但没有‘shell = True‘?
    查看>>
    Python - 如何使这个不可腌制的对象可腌制?
    查看>>
    Python - 如何在 Windows 10 上完全卸载 Anaconda?
    查看>>
    python - 如何并行化python numpy中的总和计算?
    查看>>
    Python - 如何解析 xml 响应并将元素值存储在变量中?
    查看>>
    Python - 安装了扩展的远程 Webdriver
    查看>>
    python - 将字符串中的日期与今天的日期进行比较
    查看>>
    python - 数据描述符(class 内置 get/set/delete方法 )
    查看>>
    Python - 根据值绘制彩色网格
    查看>>
    Python - 正则表达式在括号之间获取数字
    查看>>
    Python - 正则表达式在括号之间获取数字
    查看>>
    Python - 正则表达式在括号之间获取数字
    查看>>
    Python - 类 __hash__ 方法和集合
    查看>>
    Python - 轻松将文本文件内容转换为字典值/键
    查看>>
    Python - 递归和列表
    查看>>
    Python 3 读取ini文件
    查看>>
    Python 3.0 使用 turtle.onclick
    查看>>
    Python 3.10 明年发布,看看都有哪些新特性?
    查看>>
    python 3.10上安装pyqt5
    查看>>
    Python 3.12 正式发布了!
    查看>>