本文共 1866 字,大约阅读时间需要 6 分钟。
要使用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() pip install psycopg2命令安装模块。CREATE TABLE语句创建表单。INSERT INTO语句将数据插入数据库。SELECT语句查询数据,并对返回结果进行处理。通过以上步骤,可以方便地与PostgreSQL数据库进行交互。
转载地址:http://eoafk.baihongyu.com/