insert_query = u""" INSERT INTO did_you_know ( name, to_be_handled, creator, nominator, timestamp) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}') """.format("whatever", "whatever", "whatever", "whatever", "whatever") is my example.

Does every single value in a MySQL query have to contain quotes?

Would this be acceptable or not? INSERT INTO TABLE VALUES ('Hello', 1, 1, 0, 1, 'Goodbye')

Thank you.

有帮助吗?

解决方案

Your answer is NO.:) This is accepted: when the 'Hello' and 'Goodbye' is Varchar or text. and Numbers are integer or number type

INSERT INTO TABLE VALUES ('Hello', 1, 1, 0, 1, 'Goodbye');

and in your example query is like.

insert_query = "
        INSERT INTO did_you_know(
        name,to_be_handled,creator,nominator,timestamp)
        VALUES('varchar_value', interger_or_number_value, 'varchar_value');

Like That . :)

其他提示

You need to quote only character and other non-integer data types.
Integer data types need not be quoted.

If you follow the standard practice in Python, you don't have to worry about escaping; and it will also prevent other nasty issues with your database.

Python has a standard DB API that all drivers conform to. In this API, to pass arguments to queries, you need to pass them to the execute function of the cursor as a second argument, not parse them in as a string (what you are doing).

Your query, correctly written will not have to worry about quoting at all:

q = """INSERT INTO did_you_know (
        name, to_be_handled, creator, nominator, timestamp)
        VALUES (%s, %s, %s, %s, %s)"""

arg = "hello"
arg2 = "world"
cur.execute(q, ("foo","bar","zoo",arg,arg2,))
con.commit()

Keep in mind if you use any of MySQL's reserved words as table names, you need to escape them in backticks.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top