1

Please help. My code for insertion of data to a database returns with an error message:

insertVar =("INSERT INTO %a ( ticker, date, openPrice, dayHigh, dayLow, closePrice, volume ) VALUES ( %s, %s, %s, %s, %s, %s, %s)" %(stripedTicker))

TypeError: not enough arguments for format string.

The code is

def insertData (data):
    insertVar =("INSERT INTO %a ( ticker, date, openPrice, dayHigh, dayLow, closePrice, volume ) VALUES ( %s, %s, %s, %s, %s, %s, %s)" %(stripedTicker))
    cur.execute(insertVar, data)
    conn.commit()

The variable data = ['Access Bank Plc', '2018-12-15', '7.45', '7.50', '7.45', '7.45', '18,152,221'] Any help on how to resolve this will be greatly appreciated. Thanks.

3
  • In your string you want to insert 8 strings, but your list only has 7 elements Commented Dec 15, 2018 at 12:59
  • What I have is 7 strings ( ticker, date, openPrice, dayHigh, dayLow, closePrice, volume ), and that is what I want insert. I intentionally skipped my id column as is auto_increment. Commented Dec 15, 2018 at 13:38
  • Please, assist show me the 8 strings. Thanks. Commented Dec 15, 2018 at 13:40

1 Answer 1

3

The error is informing you that your insertVar variable is expecting 8 arguments from stripedTicker. I'm guessing your stripedTicker variable only contains one argument to format %a. (And you want to keep the %s's to be formatted by cur.execute().)

For example, this would work

print('%s %s' % ('a', 'b')) # prints 'a b'

but the following wouldn't

print('%s %s' % ('a')) # TypeError: not enough arguments for format string

since the % formatter expects arguments to fill each %s. Your current way of formatting the string won't work unless you add extra percentage signs (%) at the front of your %s arguments. For example

print('%s %%s' % ('a')) # prints 'a %s'

Thus, adding extra % to your %s's...

insertVar = ("INSERT INTO %a ( ticker, date, openPrice, dayHigh, dayLow, closePrice, volume ) \  
    VALUES ( %%s, %%s, %%s, %%s, %%s, %%s, %%s)" % (stripedTicker))

or opt for another way of formatting, for example, using f-strings:

insertVar = f"INSERT INTO {stripedTicker} ( ticker, date, openPrice, dayHigh, dayLow, closePrice, volume ) \  
    VALUES ( %s, %s, %s, %s, %s, %s, %s)"

or .format()

insertVar = "INSERT INTO {} ( ticker, date, openPrice, dayHigh, dayLow, closePrice, volume ) \  
    VALUES ( %s, %s, %s, %s, %s, %s, %s)".format(stripedTicker)
Sign up to request clarification or add additional context in comments.

1 Comment

Wow! Thanks a million times, TrebuchetMS. Your solution worked fine. Thanks. I'm very grateful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.