Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question

6 Answers

up vote 8 down vote accepted

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 :)

share|improve this answer
any ideas on what I put below? – Specto Apr 22 '09 at 1:32
I responded :) You may want to post your schema for the table. – Trey Stout Apr 22 '09 at 1:33
2  
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 Apr 22 '09 at 1:34
You realize this is vulnerable to SQL injection, right? – Rick Copeland Apr 22 '09 at 1:35
That's fine in this case. SQL injections are no issue, this is a back end. – Specto Apr 22 '09 at 1:38
show 3 more comments

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).

share|improve this answer
1  
will this work where the var1 and var2 have charecters like " or ' . – sheki Oct 24 '11 at 11:53

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 (with escaping)

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 eg. python-sqlite).

share|improve this answer
1  
This is a backend, shouldn't have to worry about sql injections on myself. – Specto Apr 22 '09 at 1:39
4  
The correct example will also perform faster in many cases – Rick Copeland Apr 22 '09 at 1:53
6  
+1: This really should be the accepted answer, I came here to find out how to use parameterized queries with MySQLdb, and that's exactly it, thanks – Dyppl Jul 1 '11 at 8:39
1  
+1 wow so subtle, can't understand why they didn't use ? – Bryan Hunt Mar 28 '12 at 19:48
+1: I'm with @Dyppl on this one... – astex Jan 20 at 0:38
show 1 more comment

Actually, even if your variable (SongLength) is numeric, you will still have to format it with %s in order to bind the parameter correctly. If you try to use %d, you will get an error. Here's a small excerpt from this link http://mysql-python.sourceforge.net/MySQLdb.html:

To perform a query, you first need a cursor, and then you can execute queries on it:

c=db.cursor()
max_price=5
c.execute("""SELECT spam, eggs, sausage FROM breakfast
          WHERE price < %s""", (max_price,))

In this example, max_price=5 Why, then, use %s in the string? Because MySQLdb will convert it to a SQL literal value, which is the string '5'. When it's finished, the query will actually say, "...WHERE price < 5".

share|improve this answer

This works for me:

name="sawan"
cursor.execute('insert into s values("%s")'%(name))
share|improve this answer
Care to add some more information and detailes? There is an accepted answer with 6 upvotes and another one with 40 upvotes and lot of details. What your answer adds to the previous ones? – Yaroslav Oct 4 '12 at 6:34
3  
DO NOT do this. It adds an SQL injection hole! – sirbrialliance Mar 12 at 17:45

As an alternative to the chosen answer, and with the same safe semantics of Marcel's, here is a compact way of using a Python dictionary to specify the values. It has the benefit of being easy to modify as you add or remove columns to insert:

  meta_cols=('SongName','SongArtist','SongAlbum','SongGenre')
  insert='insert into Songs ({0}) values ({1})'.
        .format(','.join(meta_cols), ','.join( ['%s']*len(meta_cols) ))
  args = [ meta[i] for i in meta_cols ]
  cursor=db.cursor()
  cursor.execute(insert,args)
  db.commit()

Where meta is the dictionary holding the values to insert. Update can be done in the same way:

  meta_cols=('SongName','SongArtist','SongAlbum','SongGenre')
  update='update Songs set {0} where id=%s'.
        .format(','.join([ '{0}=%s'.format(c) for c in meta_cols ]))
  args = [ meta[i] for i in meta_cols ]
  args.append( songid )
  cursor=db.cursor()
  cursor.execute(update,args)
  db.commit()
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.