Home > Back-end >  IndexError out of range on Python
IndexError out of range on Python

Time:03-06

I have a python code to insert data into my database. Here is the line: query = 'insert into 1_recipe values({0})'. I used {0} to pass all data from my CSV file. It works perfectly before I use sys.argv in my code. Here is the new code :

import sys

nomor = sys.argv[1]

.....
    query = "insert into {idnumber}_recipe values ({0})".format(idnumber = nomor)
    query = query.format(','.join(['%s'] * len(data)))
.....

When I run this code, always back with this error :

'query = "insert into {idnumber}_recipe values ({0})".format(idnumber = nomor)
IndexError: Replacement index 0 out of range for positional args tuple'

How to fix it? Thanks.

Update: I already found the answer. Thank you

CodePudding user response:

You are only passing one argument to the format() function:

.format(idnumber = nomor)

The format function doesn't have a value to give to the ({0}) part of the formatted string. Either give another value or change it so it will use idnumber as well

CodePudding user response:

You can look at query development for formatting here.

e.g.:

insert_stmt = (
  "INSERT INTO employees (emp_no, first_name, last_name, hire_date) "
  "VALUES (%s, %s, %s, %s)"
)
data = (2, 'Jane', 'Doe', datetime.date(2012, 3, 23))
cursor.execute(insert_stmt, data)

Your code can be rewritten something like this using better formatting:

import sys

nomor = sys.argv[1]

data_str_value = ','.join(['%s'] * len(data))
.....
    query = "insert into {idnumber}_recipe values ({values})".format(idnumber = nomor, values = data_str_value)
.....

Note: This code is showing only better formatting as per the example given. This query may or may not run as expected due to incorrect syntax.

  • Related