python - psycopg2 : Insert a numpy array of strings into an PostgreSQL table

标签 python mysql arrays database postgresql

请认为我是 psycopg2 的新手。我的目标是将 dtype 对象的一维 numpy 数组(其中元素只是字符串)插入到 postgresQL 表中。我的主程序将字段保存为 numpy 数组中的字符串。然后,我想将每个单独的元素添加到 postgresqL 表中的一列(或者如果您愿意,一维数组是一行)。请注意,实际数组有 36 个元素!我需要一种方法将它们全部放入。

我正在使用 cur.execute 命令,尽管我相信字符串转换存在一些问题。

Array=np.empty(3,dype=object)
Array[0]='Hello'
Array[1]='Tea?'
Array[2]='Bye'

statement= "INSERT INTO testlog (field1,field2,field3) VALUES (%s)" #Etc.
cur.execute(statement,Array)

我收到错误:

cur.execute(statement,Array)
TypeError: not all arguments converted during string formatting

还尝试过:

cur.executemany('INSERT INTO testlog VALUES ( %s )', [[v] for v in Array ]

谢谢

最佳答案

您的语句应包含所有值的占位符:

statement= "INSERT INTO testlog (field1,field2,field3) VALUES (%s, %s, %s)"

例如:

=# create table testlog (field1 varchar(50), field2 varchar(50), field3 varchar(50))`;

然后在 python shell 中(注意 dtype 不是 dype:

Array=np.empty(3,dtype=object)
Array[0]='Hello'
Array[1]='Tea?'
Array[2]='Bye'
sql = "INSERT INTO testlog (field1, field2, field3) VALUES (%s, %s, %s)"
cur.execute(sql, [f for f in Array])
conn.commit()

在数据库中:

select * from testlog;
 field1 | field2 | field3 
--------+--------+--------
 Hello  | Tea?   | Bye
(1 row)

关于python - psycopg2 : Insert a numpy array of strings into an PostgreSQL table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25382799/

相关文章:

python - importlib 中 imp.find_module 的等价物是什么

php - mysql unhex() 不能在 linux 服务器上运行?

c++为什么数组没有长度属性

php - 从查询中获取 10 行

mysql - 否定 MySQL 查询

java - 仅在 for 循环中打印所有其他枚举值

python - 如何设置openpyxl ScatterChart的线条颜色

子集上的 Python 枚举迭代

python - 使用 Deque.popleft 作为函数的参数

php - 在 symfony 中,如何设置表单字段的值?