使用Psycopg2将值插入表

时间:2019-08-29 13:17:28

标签: python psycopg2

我正在尝试使用psycopg2将值插入到表中。我的插入查询具有列名,并且我正在使用.format方法将变量插入值中。我收到的错误如下...看来,它使用了我电子邮件中的“测试”字符串作为列。当我删除电子邮件列并仅保留account_number时,它仅插入部分随机数而不是'123456789'...我不确定为什么吗?

我遇到错误:

"    VALUES ({},{})""".format(account2, email2))
psycopg2.errors.UndefinedTable: missing FROM-clause entry for table 
"test"
LINE 2:             VALUES (123456789,test@example.com)

我也尝试过使用“%”格式,以查看其将值插入查询中的.format方法是否成功,但这种方法也不起作用。

                    elif extrareadayday_date in extrareaddays:
                        accounts_sheet = pd.read_excel("C:\\Users\\bxt058y\\PycharmProjects\\MSIT501\\MSIT\\sumbaccounts.xlsx",
                                                       sheet_name=0)
                        df = DataFrame(accounts_sheet)
                        email_address2 = df[df['cycle_day'] == current_cycle_day].email_address_test
                        account_numbers2 = df[df['cycle_day'] == current_cycle_day].account_number
                        email_address3 = df[df['cycle_day'] == current_cycle_day2].email_address_test
                        account_numbers3 = df[df['cycle_day'] == current_cycle_day2].account_number
                        for account2, email2 in zip(account_numbers2, email_address2):
                            to_file(sumbstatementfilepath, account2, 'N - NOT BILLED', 'SUMB_Statement_{}.txt'.format(account2.strip()), email2)
                            print(account2)
                            extra_read_day_confirmation_email()
                            cursor.execute("""INSERT INTO sumb_email_conf (account_number, email_address)
                            VALUES ({},{})""".format(account2, email2))
                        for account3, email3 in zip(account_numbers3, email_address3):
                            to_file(sumbstatementfilepathreadday, account3, 'N - NOT BILLED', 'SUMB_Statement_{}.txt'.format(account3.strip()),
                                    email3)
                            print(account3)
                            extra_read_day_confirmation_email2()
                            cursor.execute("""INSERT INTO sumb_email_conf (account_number,email_address)
                                        VALUES ({},{})""".format(account3, email3))
                            connection.commit()

2 个答案:

答案 0 :(得分:0)

对于psycopg2格式化,可以尝试使用mogify方法。 http://initd.org/psycopg/docs/cursor.html#cursor.mogrify

示例提示您的问题:

sql = "INSERT INTO sumb_email_conf (account_number,email_address VALUES (%s, %s)"
query = cursor.mogrify(SQL, account3, email3)
cursor.execute(query)

答案 1 :(得分:0)

如果使用python格式,则需要在SQL中用引号引起来:

cursor.execute("""INSERT INTO sumb_email_conf (account_number, email_address)
                            VALUES ({},'{}')""".format(account2, email2))

但是,最好使用数据库API:

cursor.execute("""INSERT INTO sumb_email_conf (account_number, email_address)
                            VALUES (%s,%s)""", [account2, email2])
相关问题