私は、csvデータをpostgresデータベースに取得するための高速、つまり高速で多くのコードではない方法を取得しようとしています。私は正常に動作する csvDictreader を使用して Python に読み込んでいます。次に、辞書を取得してテーブルに入れるコードを何らかの方法で生成する必要があります。テーブルには何百もの変数があることが多いため、これを自動的に実行したいと考えています。(多くの場合、データを変換する必要があり、Python が適しているため、Postgres に直接読み取りたくありません)
これは私が持っているものの一部です:
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']