I am using python to save a blogdata as an sql file .
str = "INSERT INTO TABLENAME (id,name,con) VALUES ('%d','%s','%s')" %(id,nam,con)
Here, “con” refers to the content which contains all kinds of things like single quotes , double quotes and others . So the file became like this :
INSERT INTO TABLENAME (id,name,con) VALUES('1','first','Hi I'm XXX . "435" 'sdfsd' ')
Please observer last part of above line, as it contains different quotes, the sql file will not be executed if i use the above format . What is the solution for this ? Will provide more information if necessary .
Thanks
What you want to do is sanitize your queries, to avoid having sql injections and having valid queries. In order to do this, you need to escape literal values, like strings. There are libraries for this. In your case, and that’s the least safe option, you could use
reprfor strings, which will do the job. There are better options, DON’T USE THIS, use what your database drivers offer you. For example:If you are using MySQL, you could use
python-mysql(MySQLdb) to escape your strings, so that you can generate sql files which you can execute safely.When using
MySQLdb.escape_string, you are sure the characters are safe, then you use the format string you were using. Also, make sure you do this for ALL values, and not only those who are “risky”.If you are not using MySQL, check this out for postgresql.
If you do not want to use it directly via SQL, look into libraries like MySQLdb for MySQL, etc.