2

Insert query for string having \" character in it in mysql db-

How to write insert query for string such as:

This is the string i want to insert into my table,

reg="item-cell\"(.*?)</span></div>"

cur = db.cursor()
query='INSERT into table_name(col_name) values("%s")'%(reg)
cur.execute(query)
cur.close()

Below is the error:

_mysql_exceptions.ProgrammingError: (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'(.*?)</span></div>")\' at line 1')

I know its something related to escape character, but don't know how to make that work.

EDIT: This string reg is variable i.e. I am getting this string from some API and I want to insert it into my database. So inserting escape characters in between the string literal will not suffice my case. I want something that can generalize single quote, double quote or one double quote(eg. reg) all these cases.

I hope I made my point clear.

EDIT: This is how i am getting the value of reg(froma json file)

import urllib, json
import MySQLdb
url = "some_url"
response = urllib.urlopen(url)
data = json.loads(response.read())
for item in data["key1"]["key2"]["key3"]["key4"]:
    prop=str(item)
    reg=str(data["key1"]["key2"]["key3"]["key4"][prop]["regex"])

1 Answer 1

0

The problem is in the part where you convert the json object to string. To properly do this without altering the string you need to use json.dumps

for item in data["key1"]["key2"]["key3"]["key4"]:
    prop = json.dumps(item)
    reg = json.dumps(data["key1"]["key2"]["key3"]["key4"][prop]["regex"])
Sign up to request clarification or add additional context in comments.

8 Comments

This is good when i have just one string but what if i have thousands of such strings. Surely, we are not going to check for every string. Is there any way that can generalise this?
@ujjawlsaini I edited the answer to use raw strings, have u tried that yet?
Yeah, this works fine. But the way you have written the string "item-cell\"(.*?)</span></div>" as r"item-cell\"(.*?)</span></div>", How to write same for variable holding the string. Like say "mystr" is what i am getting from some API, now how to write for this reg= r"mystr". I know this is not correct, Hope you understand what i am asking.
It failed for this - "item-cell\"(.*?)</span></div>" resulting as" item-cell"(.*?)</span></div>"
@ujjawlsaini can you post the code that gets the string? after testing for a while, it turns out that if you get a string as input from user using 'raw_input()' python 2.x or 'input()' python 3.x it is already a raw string, the same applies if its read from a file.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.