Your true problem likes in that your "City, State"
line is a sequence of characters. You cannot directly insert a sequence of characters in SQL like this:
INSERT INTO test VALUES (My String);
Instead, you treat it like a string. MySQL expects strings to be wrapped in single quotes, so you would change the above to:
INSERT INTO test VALUES ('My String');
Now you've got the string 'My String'
stored. Now, generating that dynamically isn't much different, except you're going to have to make sure it's wrapped in single quotes - like:
loc = "City, State"
sql = "INSERT INTO test VALUES ('" + loc + "');"
Notice the single quotes around where I'm inserting location.
The rest is additional information
This is a dangerous operation though because I'm allowing any value to directly enter my database, even if that values is "'); DROP DATABASE test; -- "
which would do some damage. You'd think it's harmless but after plugged in you get:
INSERT INTO test VALUES(''); DROP DATABASE test; -- ');
And so now I've just lost all of my data. To fix this you want to escape values before putting them in your database which is as simple as MySQLdb.escape_string(str)
. Then you just:
loc = "'); DROP DATABASE test; -- "
loc = MySQLdb.escape_string(loc);
sql = "INSERT INTO test VALUES ('" + loc + "');"
And the result is:
INSERT INTO test VALUES ('\'); DROP DATABASE test; -- ');
Which will not result in any kind of damage to your database. This is not the only vulnerability that you open yourself to and it's a very simplified example.