user3702643 user3702643 - 11 months ago 83
MySQL Question

Python insert into %s MySQL

I am trying to insert some data into a database using the variable test as the table name. But unfortunately I cant seem to achieve this. Can anyone help me out?

From my raise I am getting:

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

My code:

test = "hello"
# Open database connection
db = MySQLdb.connect("","admin","password","table" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.
sql = ("""INSERT INTO %s (name,
age, gender)
VALUES (%s, %s, %s)""",(test))
# Execute the SQL command
cursor.execute(sql, (name, age, gender))

# disconnect from server

Answer Source

Something like this will work:

    sql = """INSERT INTO %s (name, age, gender)
    VALUES (%s, %s, %s)""" % (test, "%s", "%s", "%s")

You need to separate Python's string substitution from MySQL's parameter substitution. The above is a crude approach, but minimally different from your own code.