I’m trying to handle a file address within my python program and pass it to MySQL.
I have found out that I need to use raw strings for the address so it gets to MySQL intact.
This works:
myFilePath = r"'D:\\folder\\file.csv'"
sqlStatement = r"LOAD data local INFILE %s INTO TABLE test ...);" % (myFilePath)
However, I’m creating a GUI and want the pathname to be changable. So I’m trying to convert a normal filepath into the right format, but I can’t get it done.
How can I convert
filePath = "D:\folder\file.csv"
into the exact same format like myFilePath above?
The best I’ve come up with so far is
myFilePath = r'r"' + "'" + filePath + "'"
But I still need to double the existing backslashes, and I can’t find any way to do it. I’ve tried iterating, like this:
myFilePath = ""
for i in range(len(filePath)):
if i == "\\":
myFilePath += "\\\\"
else:
myFilePath += filePath[i]
But that doesn’t work, probably because of the escape nature of backslashes.
Just using raw string again creates more backslashes than I want, and I’m out of my depth.
Can anyone help me, please?
You shouldn’t be using string formatting to create a SQL statement in the first place. Once you use the db interface the right way, the problem goes away:
Using string formatting for SQL statements is just opening yourself up to SQL injection attacks.