将列转换为 postgresql 数据库
converting columns to postgresql database
假设我在 python 中有一个等长的列列表(在下面的示例中,每列有 4 个元素,但在我的实际工作中,每列有大约 500 多个元素):
col0 = [1, 12, 23, 41] # also used as a primary key
col1 = ['asdas','asd', '1323', 'adge']
col2 = [true, false, true, true]
col4 = [312.12, 423.1, 243.56, 634.5]
并且我已经定义了一个 postgresql table,其中包含列:Col0(整数,也是主键)、Col1(字符变化)、Col2(布尔值)、Col3(数字)
我编写了以下代码来连接到 postgresql 数据库(似乎运行良好):
import psycopg2
...
conn = psycopg2.connect("dbname='mydb' user='myuser' host='localhost' password = 'mypwd')
cur = conn.cursor()
现在假设我想将列推送到 postgresql table myt
我希望行填充为 :
Col1 Col2 Col3 Col4
1 'asdas' true 312.12
12 'asd' false 423.1
...
我在 SO such as this one 上看到了示例,其中示例用于从 csv 文件读取:
for row in reader:
cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)", (variable1, variable2))
(a) 我可以为我的案例采用类似的东西吗?这行得通吗:
for i in range(0, len(col0)):
cur.execute("INSERT INTO myt (Col1, Col2, Col3, Col4) VALUES (%??, %s, %??, %f)", (col0[i], col1[i], col2[i], col3[i]))
(b) 如果是,当相应的 postgresql 类型为整数、布尔值和数字时,python 整数、布尔值、浮点数类型的类型说明符是什么?
(c) 此外,如果我有 40 个 table,而不是 4 个 table,会怎样?是不是要写这么长的一行:
"INSERT INTO myt (Col1, Col2, ..., Col40) VALUES (%d, %s, ..., %f)", (col0[i], ...))
a,b:
是的,这会起作用,psycopg2 使用 %s
来表示所有类型,这就是它的工作方式。(所以不要使用 %??
等...)
c:
"insert into {t} ({c}) values ({v})".format(
t=tablename,
c=','.join(columns_list),
v=','.join(['%'] * len(columns_list))
使您更接近通用插入表达式,但您仍然需要循环...
假设我在 python 中有一个等长的列列表(在下面的示例中,每列有 4 个元素,但在我的实际工作中,每列有大约 500 多个元素):
col0 = [1, 12, 23, 41] # also used as a primary key
col1 = ['asdas','asd', '1323', 'adge']
col2 = [true, false, true, true]
col4 = [312.12, 423.1, 243.56, 634.5]
并且我已经定义了一个 postgresql table,其中包含列:Col0(整数,也是主键)、Col1(字符变化)、Col2(布尔值)、Col3(数字)
我编写了以下代码来连接到 postgresql 数据库(似乎运行良好):
import psycopg2
...
conn = psycopg2.connect("dbname='mydb' user='myuser' host='localhost' password = 'mypwd')
cur = conn.cursor()
现在假设我想将列推送到 postgresql table myt
我希望行填充为 :
Col1 Col2 Col3 Col4
1 'asdas' true 312.12
12 'asd' false 423.1
...
我在 SO such as this one 上看到了示例,其中示例用于从 csv 文件读取:
for row in reader:
cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)", (variable1, variable2))
(a) 我可以为我的案例采用类似的东西吗?这行得通吗:
for i in range(0, len(col0)):
cur.execute("INSERT INTO myt (Col1, Col2, Col3, Col4) VALUES (%??, %s, %??, %f)", (col0[i], col1[i], col2[i], col3[i]))
(b) 如果是,当相应的 postgresql 类型为整数、布尔值和数字时,python 整数、布尔值、浮点数类型的类型说明符是什么?
(c) 此外,如果我有 40 个 table,而不是 4 个 table,会怎样?是不是要写这么长的一行:
"INSERT INTO myt (Col1, Col2, ..., Col40) VALUES (%d, %s, ..., %f)", (col0[i], ...))
a,b:
是的,这会起作用,psycopg2 使用 %s
来表示所有类型,这就是它的工作方式。(所以不要使用 %??
等...)
c:
"insert into {t} ({c}) values ({v})".format(
t=tablename,
c=','.join(columns_list),
v=','.join(['%'] * len(columns_list))
使您更接近通用插入表达式,但您仍然需要循环...