This is similar with imploding a list for use in a python MySQLDB IN clause and python list in sql query as parameter, but their list's elements are all integer.
param = []
param.append(post.title)
param.append(post.count_vote)
param.append(post.last_reply_time)
param.append(post.last_replyer_id)
param.append(post.poster_id)
param.append(post.content)
param.append(post.plain_content)
param.append(post.relate_unit)
query = "INSERT INTO post (title, countVote, lastReplyTime, lastReplyerId, posterId, content, plainContent, relateUnit) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}');".format(*param)
cursor.execute(query)
The elements have many types such as int, str and None. What stucks me is the string type, the string may contain '
and "
. I just simply replaced '
with "
before. However, I accidently saw some C code snippet like char ch = 'a';
in content field. '
replacement will disobey the syntax.
I want to know is there a way to insert string without modification? I come across the idea to replace '
with \'
, is that a good idea?
I also try to replace {0}
etc. in the query string with ?
query = "INSERT INTO post (title, countVote, lastReplyTime, lastReplyerId, posterId, content, plainContent, relateUnit) VALUES (?, ?, ?, ?, ?, ?, ?, ?);"
cursor.execute(query, tuple(param))
# cursor.execute(query, [param,])
Both give me the error
_mysql_exceptions.ProgrammingError: not all arguments converted during string formatting