Python 如何在 PostgreSQL 中使用变量
How to use variables in PostgreSQL in Python
我的声音 table 有 7 列:Start_Time
、End_Time
、Salience_Label
、Class_label
、Bitrate
、Bitdepth
, Samplerate
.
我想使用命令
向 table 中插入一些值
cursor.execute("INSERT INTO Sounds VALUES (%s, %s, %s, %s, %s, %s, %s)",(start_time, end_time, salience_label, class_label, samplerate, bitrate, bitdepth))
try:
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
.... doing staff for getting values for my variables ...
cursor.execute("INSERT INTO Sounds VALUES (%s, %s, %s, %s, %s, %s, %s)",(start_time, end_time, salience_label, class_label, samplerate, bitrate, bitdepth))
print "Connected!\n"
except:
print "I am unable to connect to the database"
cursor.close()
conn.close()
print('Close conection')
虽然测试不捕获异常。将参数设为单个元组,因为 Psycopg 会将其调整为记录。使用 mogrify
检查发送到服务器的内容:
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
insert = "insert into Sounds values %s"
parameters = (
start_time, end_time, salience_label,
class_label, samplerate, bitrate, bitdepth
)
print cursor.mogrify(insert, (parameters,))
cursor.execute(insert, (parameters,))
conn.commit()
cursor.close()
conn.close()
顺便说一句,好的做法是命名将接收数据的列,如:
insert into t (col_a, col_b) values (1, 'a')
这样可以避免一些问题。
我的声音 table 有 7 列:Start_Time
、End_Time
、Salience_Label
、Class_label
、Bitrate
、Bitdepth
, Samplerate
.
我想使用命令
向 table 中插入一些值cursor.execute("INSERT INTO Sounds VALUES (%s, %s, %s, %s, %s, %s, %s)",(start_time, end_time, salience_label, class_label, samplerate, bitrate, bitdepth))
try:
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
.... doing staff for getting values for my variables ...
cursor.execute("INSERT INTO Sounds VALUES (%s, %s, %s, %s, %s, %s, %s)",(start_time, end_time, salience_label, class_label, samplerate, bitrate, bitdepth))
print "Connected!\n"
except:
print "I am unable to connect to the database"
cursor.close()
conn.close()
print('Close conection')
虽然测试不捕获异常。将参数设为单个元组,因为 Psycopg 会将其调整为记录。使用 mogrify
检查发送到服务器的内容:
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
insert = "insert into Sounds values %s"
parameters = (
start_time, end_time, salience_label,
class_label, samplerate, bitrate, bitdepth
)
print cursor.mogrify(insert, (parameters,))
cursor.execute(insert, (parameters,))
conn.commit()
cursor.close()
conn.close()
顺便说一句,好的做法是命名将接收数据的列,如:
insert into t (col_a, col_b) values (1, 'a')
这样可以避免一些问题。