0

I want to insert the variable bob, and dummyVar into my table, logger. Now from what I can tell all I should need to do is, well what I have below, however this doesn't insert anything into my table at all. If I hard-code what should be written (using 'example' then it writes example to the table, so my connection and syntax for inserting is correct to this point). Any help would be more than appreciated!

conn = mysql.connector.connect(user='username', password='password!',
                              host='Host', database='database')

cursor = conn.cursor()

bob = "THIS IS AN EXAMPLE"
dummyVar = "Variable Test"

loggit = ("""
        INSERT INTO logger (logged_info, dummy)
        VALUES
            (%s, %s)
    """, (bob, dummyVar))

cursor.execute(loggit)
conn.commit()

I have also tried this:

loggit = ("""
        INSERT INTO logger (logged_info, dummy)
        VALUES
            (%(bob)s,(Hello))
    """, (bob))

and:

bob = "THIS IS AN EXAMPLE"
dummyVar = "Variable Test"

loggit = ("""
        INSERT INTO logger (logged_info, dummy)
        VALUES
            (%s, %s)
    """, (bob, dummyVar))

cursor.execute(loggit, (bob, dummyVar))
conn.commit()


cursor.execute(loggit, (bob, dummyVar))

conn.commit()
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Steve Byrne
  • 1,320
  • 1
  • 16
  • 29
  • In addition to your main problem (which Martijn Pieters answers), you've got another one in your last example: `(bob)` is not a tuple of one element, it's the same thing as `bob`. You need to write `(bob,)`. – abarnert May 12 '13 at 11:22
  • Does this answer your question? [MySQL parameterized queries](https://stackoverflow.com/questions/775296/mysql-parameterized-queries) – Henry Woody May 21 '22 at 01:24

1 Answers1

4

You need to pass the SQL statement and the parameters as separate arguments:

cursor.execute(loggit[0], loggit[1])

or use the variable argument syntax (a splat, *):

cursor.execute(*loggit)

Your version tries to pass in a tuple containing the SQL statement and bind parameters as the only argument, where the .execute() function expects to find just the SQL statement string.

It's more usual to keep the two separate and perhaps store just the SQL statement in a variable:

loggit = """
        INSERT INTO logger (logged_info, dummy)
        VALUES
            (%s, %s)
    """
cursor.execute(loggit, (bob, dummyVar))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343