来自python的数据显示在一列而不是ppostgresqll上的两列

时间:2017-11-22 14:06:20

标签: python sql eclipse postgresql pydev

表格显示但所有数据都显示在HY下。我希望第19行显示在HY和第20行下显示在AY下。事实上,AY列正在创建,但所有行都显示[null]

#!/usr/bin/python
# -*- coding: utf-8 -*-

import psycopg2
import sys
import csv
from itertools import count
path = r'C:\Users\sammy\Downloads\E0.csv'
with open(path, "r") as csvfile:
    readCSV = csv.reader(csvfile, delimiter=",")
    firstline = 1
    con = None
    con = psycopg2.connect("host='localhost' dbname='football' user='postgres' password='XXX'")   
    cur = con.cursor()
    cur.execute("DROP TABLE testtest1234")
    cur.execute("CREATE TABLE testtest1234 (HY INTEGER, AY INTEGER)")

try:
    for row in readCSV:
        if firstline:
            firstline=0
            continue 
        new_data = row[19]
        newer_data = row[20]
        print(new_data)
        print(newer_data)
        cur.execute("INSERT INTO testtest1234 values ("+new_data+"), ("+newer_data+")")
except psycopg2.DatabaseError as e:
    if con:
        con.rollback() 
        print ("Error %s % e", e)
        sys.exit(1) 
finally:
    if con:
        con.commit()
        con.close()

print(" ".join(row))
out=open("new_data.csv", "w")
output = csv.writer(out)

for row in new_data:
    output.writerow(row)

out.close()

1 个答案:

答案 0 :(得分:1)

你形成查询的方式对我来说是错误的,这就是你如何使它工作。

创建要插入表中的数据元组:

data = (new_data, newer_data)

然后创建查询语句:

query =  "INSERT INTO items (HY, AY) VALUES (%s, %s);"

然后您可以执行以下查询:

cursor = conn.cursor()
cursor.execute(query, data)

然后提交它:

conn.commit()

您在此处编辑的代码:

for row in readCSV:
    if firstline:
        firstline=0
        continue
    new_data = row[19]
    newer_data = row[20]
    data = (new_data, newer_data)
    query = "INSERT INTO testtest1234 (HY, AY) VALUES (%s, %s);"
    print(new_data)
    print(newer_data)
    cursor = con.cursor()
    cursor.execute(query, data)