gpt4 book ai didi

python - 使用python将行插入Postgresql

转载 作者:搜寻专家 更新时间:2023-10-30 20:34:23 25 4
gpt4 key购买 nike

我使用 python 在 postgreqsl 中创建了一个表,并想用包含不同数据类型的随机数据集填充它。但我收到错误“并非所有参数在字符串格式化期间都已转换”。任何人都知道我做错了什么。我已阅读其他帖子,但找不到解决方案。

创建表

def create_tables():
""" create table in the PostgreSQL database"""
commands = (
"""
Create TABLE flight_observations(
time TIMESTAMP,
numDayofweek INTEGER,
numHour INTEGER,
ac_type TEXT,
adep TEXT,
ades TEXT,
curr_sect TEXT,
lon_t FLOAT(6),
lat_t FLOAT(6),
vg_t INTEGER,
hdot_t FLOAT8,
bearing FLOAT8,
WCA FLOAT8,
ws FLOAT8,
wd FLOAT8,
temp INTEGER
)
""")
conn = None
try:
# connection string
conn_string = "host='localhost' dbname='postgres' user='postgres' password='xxxx'"
# print connection string to connect
print "Connecting to database\n ->%s" % (conn_string)
# read the connection parameters
params = Config()
# connect to the PostgreSQL server
conn = psycopg2.connect(conn_string)
cur = conn.cursor()
# create table one by one

cur.execute(commands)
# close communication with the PostgreSQL database server
cur.close()
# commit the changes
conn.commit()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()

数据

flight_obs = ['2016-07-01 16:42:21', 'A319', 'EDDB', 'EGKK', 'EDYYSOLX', 11.071111, 52.366389, 206.5938752827827, 5.55, 268.9576458923286, 5.238123301016344, 29.257257205897805, 234.0554644610864, 221.8523282183259]

填表

def insert_flight_list(flight_obs):
sql = "INSERT INTO flight_observations(time, ac_type, adep, ades, curr_sect, lon_t, lat_t, vg_t, hdot_t, bearing, wca, ws, wd, temp) VALUES ( %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
conn = None
try:
# connection string
conn_string = "host='localhost' dbname='postgres' user='postgres' password='xxxx'"
# print connection string to connect
print "Connecting to database\n ->%s" % (conn_string)
# read database configuration
params = Config()
# connect to the PostgreSQL database
conn = psycopg2.connect(conn_string)
# create a new cursor
cur = conn.cursor()
# execute the INSERT statement
cur.executemany(sql, flight_obs)
conn.commit()
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()

insert_flight_list(flight_obs)

不确定为什么这篇文章中的 try 语句没有缩进。它们在 python 代码中缩进

最佳答案

我认为问题出在 cur.executemany(sql, flight_obs) 上。文档说:

executemany(sql, vars_list)

Execute a database operation (query or command) against all parameter tuples or mappings found in the sequence vars_list.

所以它实际上相当于:

for i in flight_obs:
cur.execute(sql, i)

因为 flight_obs 是一个字符串列表,而不是元组/映射,所以您最终会得到如下内容:

cur.execute(sql, '2016-07-01 16:42:21')
cur.execute(sql, 'A319')
cur.execute(sql, 'EDDB')

简单的修复 - 只需将 cur.executemany 替换为 cur.execute 就可以了。

关于python - 使用python将行插入Postgresql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48505015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com