user3702643 user3702643 - 15 days ago 7
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("127.0.0.1","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))
try:
# Execute the SQL command
cursor.execute(sql, (name, age, gender))
db.commit()
except:
raise
db.rollback()


# disconnect from server
db.close()

Answer

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.

Comments