I am trying to write a string to a file. This file will be a query to Microsoft's SQL server, so it must follow a specific format. This is where my problem comes in.
Assuming the rest of the code is correct, I have my write method like so:
file.write("INSERT INTO SAMPLE_TABLE (int_value, string_value, comment)\n"
"VALUES (%d, '%s', '%s')\n\n"
% (row["int_value"], row["string_value"], row["comment"]))
As you can see, I need to put quotations around %s
because that is the syntax of the query. I should also mention that I am developing a GUI. The user has the option to enter in a comment. If the user does not enter anything, row["comment"]
will be None. However, because that I have quotations around %s
, it will write 'None'
, which will be a string in the database as apposed to None
, which translates into NULL in the database, which is what I want.
I could do something like this:
if row["comment"] is None:
file.write("INSERT INTO SAMPLE_TABLE (int_value, string_value, comment)\n"
"VALUES (%d, '%s', %s)\n\n"
% (row["int_value"], row["string_value"], row["comment"]))
else:
file.write("INSERT INTO SAMPLE_TABLE (int_value, string_value, comment)\n"
"VALUES (%d, '%s', '%s')\n\n"
% (row["int_value"], row["string_value"], row["comment"]))
but that's two lines of code. And what if later on I realize that more than one value could be None? I'll have to check every single case! I need to make this dynamic.
Any help is appreciated.