0

First I extracted a list of colleges from a college website in the form of tuple of tuples:

(('name1', 'address1'), ('name2', 'address2'), ('name3', 'address3'))

then I want to write this is in a database named 'sample' and in table 'collegelist'. Table has two fields (name varchar(400) not null, address varchar(500)):

Here is the code:

for college in tuples:
   cursor.execute('INSERT INTO collegelist (name, address) VALUES ("%s", "%s")') %(college[0], college[1])
   db.commit()
db.close()

But it always give following TypeError:

TypeError: unsupported operand type(s) for %: 'long' and 'tuple'

I also tried inserting only names and leaving addresses then I get following type Error:

TypeError: unsupported operand type(s) for %: 'long' and 'str'

Now i don't understand from where 'long' type came. There are only strings and tuples in the program.

Note: Names and addresses of colleges have single quotes, double quotes, dash, period.

Why is this error coming and how can I remove it? Thanks in advance.

1 Answer 1

1

cursor.execute('INSERT INTO collegelist (name, address) VALUES ("%s", "%s")') <--

At that point, you have closed the call to execute. Also, you should pass the arguments to execute, and never, ever, EVER parse them into the query.

q_insert = "INSERT INTO collegelist (name,address) VALUES (%s,%s)"
for college in tuples:
    cursor.execute(q_insert,(college[0], college[1]))
    db.commit()
Sign up to request clarification or add additional context in comments.

1 Comment

Passing parameter values to execute() helps prevent SQL injection attacks, because escape characters are interpreted as part of the value, and cannot influence the query involved.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.