pyscopg2: Is it possible to dynamically add %s in loop

前端 未结 1 1620
走了就别回头了
走了就别回头了 2021-01-28 11:03

I am trying to create a method in python insert records into a table passing in a list of column names, and an associated list of records.

I was able to set it up where

相关标签:
1条回答
  • 2021-01-28 11:12

    You can use sql.Placeholder, to populate the sql statement with the amount of %s-placeholders you need:

    def load_table(dbname,table_name,fields,records):
            con, cur = create_connection('foo')
            query = sql.SQL("insert into {} ({}) values ({})").format(
                sql.Identifier(table_name),
                sql.SQL(', ').join(map(sql.Identifier, fields)),
                sql.SQL(', ').join(sql.Placeholder() * len(fields)))
            print(query.as_string(con))
    
    
    if __name__ == '__main__':
        dbname = '...'
        table_name = 'messages'
        fields = ['user_id', 'message_type', 'message_title']
        records = [['12345', 'json', 'my first message'], ]
    
    load_table(dbname,table_name,fields,records)
    

    Output:

    insert into "messages" ("user_id", "message_type", "message_title") values (%s, %s, %s)
    
    0 讨论(0)
提交回复
热议问题