简体   繁体   中英

How to insert string into mysql using python correctly?

I'm quite new to python and mysql. When I try to insert some records with fields of string, I failed to insert them into mysql because it always report error like: ProgrammingError: (1064, 'You have an error in your SQL syntax . I am quite confused. Occasionlly, I find it works by add additional "" to the string field, like the following:

history_market_table_name = 'my_test'
f = ['field_a', 'field_b', 'field_c', 'field_d']
r = ['a', 'b', 'c', 'd']
my_time = "'" + str(datetime.now()) + "'"
target_sql = "insert into %s (time, %s, %s, %s, %s) values(%s, %s, %s, %s, %s)"  % (
history_market_table_name, f[0], f[1], f[2], f[3], my_time, repr(r[0]), repr(r[1]), repr(r[2]), repr(r[3]))

Sorry the codes are quite tedious. Moreover, there must be something wrong with my method -- it couldn't be so stupid to insert fields with string type! Look at the my_time variable, how ridiculous.

Any one please explain how to correctly insert string into mysql with python. I am quit new. So please give a correct answer and detailed explaination is highly appreciated.

Change your format string to

"insert into %s (time, %s, %s, %s, %s) values(%s, '%s', '%s', '%s', '%s')"

Ie, single quotes around the otherwise-unquoted string values you're inserting -- and lose the repr calls after the % . This will still fail if you're inserting a string value which contains a ' character... there are better ways but they don't let you parameterize the table name and field names (which is a truly peculiar requirement...), only the values .

Added: as the OP requires "a direct expression for the 'target_sql' variable", here it is:

fmt_str = "insert into %s (time, %s, %s, %s, %s) values(%s, '%s', '%s', '%s', '%s')"
target_sql = fmt_str % (history_market_table_name, f[0], f[1], f[2], f[3], 
                        my_time, r[0], r[1], r[2], r[3])

I think it's more readable split up this way. As for "some documents for such things" which the OP also requires, MySQL has such documents with every version (and the OP didn't mention which version he or she uses) and so does Python (ditto, ditto).

The "better way" (which however don't allow parameterizing table and field names) involve using "placeholders" in lieu of value in the SQL string, rather than string substitution.

Here, sql = "insert into my_test (time, field_a, field_b, field_c, field_d) values(%s, %s, %s, %s, %s)'

(with hard-coded, not parameterized, table and field names), and later, for a given cursor opened on the MySql DB,

cursor.execute(sql, (
    str(datetime.now()), r[0], r[1], r[2], r[3]))

with no worries about quoting nor about any potential for a "sql injection" attack.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM