Python将xml / string数据插入PostgreSql数据库

时间:2018-07-23 04:45:37

标签: python sql xml psycopg2

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...

如果有人可以提供帮助,我非常感谢。谢谢。

1 个答案:

答案 0 :(得分:0)

在python中格式化字符串时,传递的值将忽略单引号(')。 因此,您可以使用('%s')代替(%s)

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