使用psycopg2读取csvData的好方法

时间:2010-08-26 00:26:09

标签: python psycopg2

我正在尝试快速而不是很多代码,以便将csv数据导入postgres数据库。我正在使用csvDictreader阅读python,它工作正常。然后我需要生成代码以某种方式获取dicts并将其放入表中。我想自动执行此操作,因为我的表通常有数百个变量。 (我不想直接读到Postgres,因为在很多情况下我必须转换数据,python对此有好处)

这是我的一些内容:

import psycopg2
import sys
import  itertools

import sys, csv
import psycopg2.extras
import psycopg2.extensions

csvReader=csv.DictReader(open( '/home/matthew/Downloads/us_gis_data/statesp020.csv',  "rb"),  delimiter = ',')
#close.cursor()
x = 0
ConnectionString = "host='localhost' dbname='mydb' user='postgres' password='######"
try:
    connection = psycopg2.extras.DictConnection(ConnectionString)
    print "connecting"
except:
    print "did not work"
# Create a test table with some data

dict_cur = connection.cursor()

#dict_cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);")
for i in range(1,50):
    x = x+1
    print x
    dict_cur.execute("INSERT INTO test (num, data) VALUES(%s, %s)",(x, 3.6))#"abc'def"))
   ### how to I create the table and insert value using the dictreader?

dict_cur.execute("SELECT * FROM test")
for k in range(0,x+1):
    rec = dict_cur.fetchone()
    print rec['num'], rec['data']

2 个答案:

答案 0 :(得分:4)

假设您有一个字段名称列表(可能是您可以从csv文件的标题中获取此字段):​​

fieldnames = ['Name', 'Address', 'City', 'State']

假设它们都是VARCHAR,您可以创建表“TableName”:

sql_table = 'CREATE TABLE TableName (%s)' % ','.join('%s VARCHAR(50)' % name for name in fieldnames)
cursor.execute(sql_table)

您可以插入字典“dict”中的行:

sql_insert = ('INSERT INTO TableName (%s) VALUES (%s)' % 
              (','.join('%s' % name for name in fieldnames),
               ','.join('%%(%s)s' % name for name in fieldnames)))
cursor.execute(sql_insert, dict)

或者在给出列表词典的情况下一次性完成:

dictlist = [dict1, dict2, ...]
cursor.executemany(sql_insert, dictlist)

您可以根据字段类型和DictReader的使用情况进行调整。

答案 1 :(得分:1)

我是新手,但这对我有用。我使用PG Admin来创建'testCSV'表。

import psycopg2 as dbapi

con = dbapi.connect(database="testpg", user="postgres", password="secret")

cur = con.cursor()

import csv
csvObject = csv.reader(open(r'C:\testcsv.csv', 'r'), dialect = 'excel',  delimiter = ',') 

passData = "INSERT INTO testCSV (param1, param2, param3, param4, param5) VALUES (%s,%s,%s,%s,%s);" 

for row in csvObject:  
    csvLine = row       
    cur.execute(passData, csvLine) 

con.commit()