【问题标题】:psycopg2: Insert a numpy array of strings into an PostgreSQL tablepsycopg2:将一个 numpy 字符串数组插入 PostgreSQL 表
【发布时间】:2014-10-12 12:24:43
【问题描述】:

请认为我是 psycopg2 的新手。我的目标是将 dtype 对象的 1D 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 ]

谢谢

【问题讨论】:

  • @Clodoaldo 你是对的,刚刚读到它here

标签: python mysql arrays database postgresql


【解决方案1】:

您的声明应包含所有值的占位符:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多