Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

python - special characters in MySQL causing error

Below image shows a code snippet:

            query="insert into mytable values ('%s','%s','%s','%s',%s,'%s')"
            value=(str(cr),str(cs),str(srv),str(cl),recipe["total_time"],image,name)
            print(name)
            cursor.execute(query%value)
            mydb.commit()

I have added a print(name) statement to show what exactly the "name" variable is. (its a string). On running, I get an error: enter image description here

The "paneer ki sabji | .." is the value of name. I am inserting the data in "name" into the mysql table, under a column of type "nvarchar".

Is the error because of the special character "|"? If yes, how do we fix it, and why did the "nvarchar" not take care of it?

question from:https://stackoverflow.com/questions/65648391/special-characters-in-mysql-causing-error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It has nothing to do with special characters. You're making the same mistake as so many before you; the %s is not being used the same as the old-style string formatting. Do not use string formatting to insert parameters into queries - this is open to SQL Injection. It is unfortunate that the DB API also specifies %s as valid: https://www.python.org/dev/peps/pep-0249/#paramstyle. See also MySQL parameterized queries

Now there's another issue:

query="insert into mytable values ('%s','%s','%s','%s',%s,'%s')"

Count the %s. There's 6. Now count:

(str(cr),str(cs),str(srv),str(cl),recipe["total_time"],image,name)

That's a tuple of 7 values. So how do you expect that to work with 6 placeholders? If recipes is a pd.Series then you have even more issues, but hopefully it's not.

My guessed answer:

query="INSERT INTO mytable VALUES ('%s', '%s', '%s', '%s', '%s, '%s', '%s')"
value=(str(cr), str(cs), str(srv), str(cl), recipe["total_time"], image, name)
cursor.execute(query, value)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...