views:

961

answers:

3

I am having a hard time using the MySQLdb module to insert information into my database. I need to insert 6 variables into the table.

cursor.execute ("""
            INSERT INTO Songs (SongName, SongArtist, SongAlbum, SongGenre, SongLength, SongLocation)
            VALUES
                (var1, var2, var3, var4, var5, var6)

        """)

Can someone help me with the syntax here?

Thanks guys, if figured out my other problem, db.commit().....

Some info on it here

+5  A: 

The linked docs give the following example:

   cursor.execute ("""
         UPDATE animal SET name = %s
         WHERE name = %s
       """, ("snake", "turtle"))
   print "Number of rows updated: %d" % cursor.rowcount

So you just need to adapt this to your own code - example:

cursor.execute ("""
            INSERT INTO Songs (SongName, SongArtist, SongAlbum, SongGenre, SongLength, SongLocation)
            VALUES
                (%s, %s, %s, %s, %s, %s)

        """, (var1, var2, var3, var4, var5, var6))

(If SongLength is numeric, you may need to use %d instead of %s).

Marcel Guzman
Good answer. No need for the '%d' for numeric values. MySQLdb will convert the number to a SQL literal; a string. See PEP 249 http://www.python.org/dev/peps/pep-0249/
Adam Bernier
+1  A: 

You have a few options available. You'll want to get comfortable with python's string iterpolation. Which is a term you might have more success searching for in the future when you want to know stuff like this.

Better for queries:

some_dictionary_with_the_data = {
    'name': 'awesome song',
    'artist': 'some band',
    etc...
}
cursor.execute ("""
            INSERT INTO Songs (SongName, SongArtist, SongAlbum, SongGenre, SongLength, SongLocation)
            VALUES
                (%(name)s, %(artist)s, %(album)s, %(genre)s, %(length)s, %(location)s)

        """, some_dictionary_with_the_data)

Considering you probably have all of your data in an object or dictionary already, the second format will suit you better. Also it sucks to have to count "%s" appearances in a string when you have to come back and update this method in a year :)

Trey Stout
any ideas on what I put below?
Specto
I responded :) You may want to post your schema for the table.
Trey Stout
Don't do these. They will fail unless the variables are properly quoted, which is hard to do correctly, use the answer from Marcel. The second is invalid syntax, use '%(name)s' for dictionary formatting.
Joel
You realize this is vulnerable to SQL injection, right?
Rick Copeland
That's fine in this case. SQL injections are no issue, this is a back end.
Specto
OK, -1 removed because original poster said SQL injection is OK. Though Marcel's approach is better for performance reasons, as well as not being vulnerable to injection.
Rick Copeland
Thanks for the info, been a while since I had to use a DB
Trey Stout
No problem, you can fix your example by changing the interpolation operator "%" to a ",". That basically tells the DB driver to do the interpolation for you, and the DB driver becomes responsible for appropriately quoting and escaping user input.
Rick Copeland
+3  A: 

Beware of using string interpolation for sql queries, since it won't escape the input parameters correctly and will leave your application open to sql injection vulnerabilities. The difference might seem trivial, but in reality it's huge.

Incorrect, with security issues:

c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s" % (param1, param2))

Correct:

c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s", (param1, param2))

It adds to the confusion that the modifiers used to bind parameters in a sql statement varies between different DB API implementations and that the mysql client library uses printf-style syntax instead of the more commonly accepted ? marker (used by for example python-sqlite).

Emil H
This is a backend, shouldn't have to worry about sql injections on myself.
Specto
The correct example will also perform faster in many cases
Rick Copeland