1

I wrote a program in order to dynamically update a database table but I am getting an error. I stuffed the program with whatever I know little about. Here's my code:

import MySQLdb
class data:
    def __init__(self):
        self.file123 = raw_input("Enter film: ")
        self.title_ = raw_input("Enter film: ")
        self.year = raw_input("Enter year: ")
        self.director = raw_input("Enter director: ")
a=data()

db = MySQLdb.connect(host="localhost", # your host, usually localhost
                     user="root", # your username
                      passwd="mysql", # your password
                      db="sakila") # name of the data base

cursor = db.cursor()

cursor.execute("INSERT INTO films (file123, title_, year, director) VALUES (?, ?, ?, ?)", (a.file123, a.title_, a.year, a.director))
db.commit()
db.close()

This is the error:

File "C:\Python27\maybe1.py", line 20, in <module>
 cursor.execute("INSERT INTO films (file123, title_, year, director) VALUES (?, ?, ?, ?)", (a.file123, a.title_, a.year, a.director))
      File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 184, in execute
        query = query % db.literal(args)
    TypeError: not all arguments converted during string formatting

How can I fix this issue ?

1
  • 1
    Use %s instead of ?. Commented Jun 25, 2014 at 8:55

2 Answers 2

1

You should change ? to %s.

Here is question about why mysqldb use %s instead of ?.

Sign up to request clarification or add additional context in comments.

7 Comments

i still get error as : OperationalError: (1366, "Incorrect integer value: 'a' for column 'file123' at row 1")
It's a mysql error: 'a' is not integer type, but you are trying to insert it into an integer field.
how to specifically define datatype for each field,could u provide me any example link please..which will be also helpful?
CREATE TABLE test (id INT) creates a table with one field named id whose type is INT.
if i need a string ,what should i do from the above example to enter string?
|
1

I would do it this way:

query = "INSERT INTO films (file123, title_, year, director) VALUES (%s, %s, %s, %s)" % (a.file123, a.title_, a.year, a.director)

cursor.execute(query)

Replace %s with correct data type, else it will try everything as string which might break at table level.

2 Comments

It's not a safe way to concatenate parameter like this.
why do you say its not safe?

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.