昨天我问了关于元组的这个问题: adding the same variable to a list of tuples
和@alecxe完美地回答它但问题现在是(PostgreSQL),当我试图在postgres中存储数据时我收到了以下错误:
TypeError: not all arguments converted during string formatting
我尝试的是:
country = (countries[i], )
user_info = [tuple((t,)) + country for t in zip(name, age, city)]
query = "INSERT INTO users_info (name, age, city, country) VALUES %s"
cur.executemany(query, user_info)
con.commit()
然后我收到了错误,我也尝试了以下内容:
user_info = [tuple((t,)) + country for t in zip(name, age, city, country)]
再次收到同样的错误,然后我尝试了别的东西:
user_info = [tuple((t,)) for t in zip(name, age, city, country)]
我说得对,但有一个问题(最后一列国家/地区)将所有国家/地区存储为唯一,即使我在创建数据库时没有将该列指定为唯一:
数据库结果:
name | age | city | country
-----+-----+-------+---------------
a | 1 | aaa | United States
d | 4 | ddd | UK
e | 5 | eee | Canada
创建数据库:
cur.execute("CREATE TABLE IF NOT EXISTS users_info (name VARCHAR(255) NOT NULL, age INT, city VARCHAR(255), country TEXT NOT NULL)")
即使他们来自同一个国家,我希望所有用户都能出现..
答案 0 :(得分:1)
表中有四个字段,因此在SQL语句中需要四个占位符:
country = (countries[i], )
user_info = [t + country for t in zip(name, age, city)]
query = "INSERT INTO users_info (name, age, city, country) VALUES (%s, %s, %s, %s)"
cur.executemany(query, user_info)
con.commit()