Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6385713
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T02:56:03+00:00 2026-05-25T02:56:03+00:00

Using a method (see bottom), I build an insert command to insert an item

  • 0

Using a method (see bottom), I build an insert command to insert an item (stored as a dictionary) into my postgresql database. Although, when I pass that command to cur.execute I get a syntax error. I’m really at a loss as to why this error is occurring.

>>> print insert_string
"""INSERT INTO db_test (album, dj, datetime_scraped, artist, playdatetime, label, showblock, playid, showtitle, time, station, source_url, showgenre, songtitle, source_title) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);""", (item['album'], item['dj'], item['datetime_scraped'], item['artist'], item['playdatetime'], item['label'], item['showblock'], item['playid'], item['showtitle'], item['time'], item['station'], item['source_url'], item['showgenre'], item['songtitle'], item['source_title'])

>>> cur.execute(insert_string)

psycopg2.ProgrammingError: syntax error at or near """"INSERT INTO db_test (album, dj, datetime_scraped, artist, playdatetime, label, showblock, playid, showtitle, time, station, source_url, showgenre, songtitle, source_title) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);""""
    LINE 1: """INSERT INTO db_test (album, dj, datetime_scraped, artis...

Here’s a more “eyeball-friendly” version of that insert command:

"""INSERT INTO db_test (album, dj, datetime_scraped, artist, playdatetime, label, showblock, playid, showtitle, time, station, source_url, showgenre, songtitle, source_title) 
    VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);""",
    (item['album'], item['dj'], item['datetime_scraped'], item['artist'], item['playdatetime'], item['label'], item['showblock'], item['playid'], item['showtitle'], item['time'], item['station'], item['source_url'], item['showgenre'], item['songtitle'], item['source_title'])

The method used to build the insert:

def build_insert(self, table_name, item):
    if len(item) == 0:
      log.msg("Build_insert failed.  Delivered item was empty.", level=log.ERROR)
      return ''

    #itemKeys = item.keys()
    itemValues = []
    for key in item.keys(): # Iterate through each key, surrounded by item[' '], seperated by comma
      itemValues.append('item[\'{theKey}\']'.format(theKey=key))

    sqlCommand = "\"\"\"INSERT INTO {table} ({keys}) VALUES ({value_symbols});\"\"\", ({values})".format(
      table = table_name, #table to insert into, provided as method's argument
      keys = ", ".join(item.keys()), #iterate through keys, seperated by comma
      value_symbols = ", ".join("%s" for key in itemValues), #create a %s for each key
      values = ", ".join(itemValues))

    return sqlCommand

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

EDIT:

I used Gringo Suaves suggestions, with the exception of a small change to the build_insert method (create as many %s symbols as needed based on # of keys present.

def build_insert(self, table_name, item):
  if len(item) == 0:
    log.msg("Build_insert failed.  Delivered item was empty.", level=log.ERROR)
    return ''

  keys = item.keys()
  values = [ item[k] for k in keys] # make a list of each key

  sqlCommand = 'INSERT INTO {table} ({keys}) VALUES ({value_symbols});'.format(
    table = table_name, #table to insert into, provided as method's argument
    keys = ", ".join(keys), #iterate through keys, seperated by comma
    value_symbols = ", ".join("%s" for value in values) #create a %s for each key
    )
  return (sqlCommand, values)
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T02:56:04+00:00Added an answer on May 25, 2026 at 2:56 am

    Your string is not a valid SQL statement, it contains lots of python cruft.

    I think I’ve fixed the method:

    def build_insert(self, table_name, item):
        if len(item) == 0:
          log.msg('Build_insert failed.  Delivered item was empty.', level=log.ERROR)
          return ''
    
        keys = item.keys()
        values = [ item[k] for k in keys ]
    
        sqlCommand = 'INSERT INTO {table} ({keys}) VALUES ({placeholders});'.format(
          table = table_name,
          keys = ', '.join(keys),
          placeholders = ', '.join([ "'%s'" for v in values ])  # extra quotes may not be necessary
        )
    
        return (sqlCommand, values)
    

    With some dummy data it returned the following tuple. I added a few newlines for clarity:

    ( "INSERT INTO thetable (album, dj, datetime_scraped, artist,
        playdatetime, label, showblock, playid, songtitle, time, station,
        source_url, showgenre, showtitle, source_title) VALUES ('%s', '%s',
        '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s',
        '%s', '%s');",
        ['album_val', 'dj_val', 'datetime_scraped_val', 'artist_val',
        'playdatetime_val', 'label_val', 'showblock_val', 'playid_val',
        'songtitle_val', 'time_val', 'station_val', 'source_url_val',
        'showgenre_val', 'showtitle_val', 'source_title_val'] 
    )
    

    Finally, pass it to cur.execute():

    instr, data = build_insert(self, 'thetable', item)
    cur.execute(instr, data)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I see that you can enable/disable using the EnableWindow method, but how do I
I am having problems using the update method of scala.collection.immutable.HashMap.I don't see the reason
Using extension methods for C#, how can include an AddNode method (see below) in
I'm using the tableToGrid method of jqGrid to convert an ASP.Net GridView into a
When programming against a fluent API or just using method-chaining, I've seen the style
Using the method Application.Restart() in C# should restart the current application: but it seems
Using the method presented here: http://cslibrary.stanford.edu/110/BinaryTrees.html#java 12. countTrees() Solution (Java) /** For the key
Using java I am trying to develop a method using recursion to analyze a
when using this method public List<Field> getFieldWithoutId(List<Integer> idSections) throws Exception { try { Connection
Should I be using this method of throwing errors: if (isset($this->dbfields[$var])) { return $this->dbfields[$var];

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.