0

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()
2
  • What errors are you getting? give us a clue... Commented Nov 20, 2016 at 16:14
  • @Stuart Added more information! Commented Nov 20, 2016 at 16:19

2 Answers 2

1

I don't think MySQLdb lets you use parameters for table names -- usually this is used for actual parameters (ones that are sometimes from user input and need sanitization - the name/age/gender part gets this right). You could use Python's string formats to achieve this:

sql = ("""INSERT INTO {table} (name, age, gender)
          VALUES (%s, %s, %s)""".format(table=table), (test))
Sign up to request clarification or add additional context in comments.

3 Comments

Could you explain what the .format(table=table) does? Because when I tried this I got NameError: global name 'table' is not defined
Substitute the table variable for your table's name. more info on this mechanism
I seem to get TypeError: unsupported operand type(s) for %: 'tuple' and 'tuple' when i try it
0

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.

2 Comments

I seem to get TypeError: unsupported operand type(s) for %: 'tuple' and 'tuple' when i try it
Worked great. Thank you!

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.