【问题标题】:Python insert xml/string data into PostgreSql databasePython 将 xml/字符串数据插入 PostgreSql 数据库
【发布时间】:2018-07-23 04:45:37
【问题描述】:
import psycopg2
myConnection = psycopg2.connect( host='192.168.103.124', user='dev', password='abc123', dbname='dev')
cursor = myConnection.cursor()
teststr='<test>123456</test>'
sql="insert into nlp_train_data(context_xml) VALUES ({})".format(teststr)
cursor.execute(sql)
myConnection.commit()

这是我得到的:

ProgrammingError                          Traceback (most recent call last)
<ipython-input-190-1560207a8c5d> in <module>()
      2 teststr='<test>123456</test>'
      3 sql="insert into nlp_train_data(context_xml) VALUES ({})".format(teststr)
----> 4 cursor.execute(sql)
      5 myConnection.commit()
      6 #except:

ProgrammingError: syntax error at or near "<"
LINE 1: insert into nlp_train_data(context_xml) VALUES (<test>123456...

如果有人能提供帮助,我将不胜感激。谢谢。

【问题讨论】:

  • 请不要使用 Python 的字符串格式来构建您的查询。 Pass your values as parameters insteadcursor.execute("insert into nlp_train_data(context_xml) VALUES (%s)", (teststr,))
  • @shmee 成功了,非常感谢!

标签: python sql xml psycopg2


【解决方案1】:

在 python 中格式化字符串时,传递的值会忽略单引号 (')。 所以你可以这样做 ('%s') 而不是 (%s)

sql="insert into nlp_train_data(context_xml) VALUES ('%s')" % (teststr,)

【讨论】:

  • 引用docs:Never、neverNEVER 使用 Python 字符串连接 (+) 或字符串参数插值 (@987654324 @) 将变量传递给 SQL 查询字符串。甚至在枪口下也没有。
  • @shmee:同意刚才提到的文档,如果你在execute语句中使用sql字符串,最好按照上面的指导,否则只有字符串格式你可以使用上述的答案。跨度>
  • 谢谢,但如果尝试使用您提供的 sql 插入,我得到“内部错误:当前事务已中止,命令被忽略,直到事务块结束”。
  • 你可以试试这个 sql=("insert into nlp_train_data(context_xml) VALUES ('%s')", (teststr,)) 这个错误基本上是在错误的事务没有成功回滚时出现的。
猜你喜欢
  • 2012-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-29
  • 2019-07-18
相关资源
最近更新 更多