使用python将行插入Postgresql

时间:2018-01-29 15:46:14

标签: python sql database postgresql

我使用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代码中缩进

2 个答案:

答案 0 :(得分:1)

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

  

executemany(sql,vars_list)

     

对序列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,它就可以正常工作。

答案 1 :(得分:0)

转动你的" flight_obs"在将它传递给executemany()

之前进入元组
cur.executemany(sql, tuple(flight_obs))
顺便说一下,你想要" exeutemany"或者只是"执行"?