Python:插入mysql数据库

时间:2015-10-04 06:14:28

标签: python mysql

我正在使用Ejabberd xmpp / jabber服务器而我正试图使用​​Python将数据插入到mysql数据库中

我正在做的是:

username = "user1"
email = "user1@domain.tld"
vCard = ("<vCard xmlns='vcard-temp'><VERSION>3.0</VERSION><ADR><HOME/></ADR><ADR><WORK/></ADR><TEL><HOME/></TEL><TEL><WORK/></TEL><TEL><FAX/></TEL><TEL><CELL/></TEL><EMAIL><HOME/><USERID>%s</USERID></EMAIL><EMAIL><WORK/></EMAIL><JABBERID></JABBERID><ORG><ORGUNIT/></ORG><PRODID></PRODID></vCard>" % (email))

import MySQLdb as mdb
db = mdb.connect('localhost', 'test1', 'test1', 'test1')
try:
    cur = db.cursor()
    cur.execute("INSERT INTO vcard(username,vcard) VALUES('%s', '%s')" % (username, vCard))
except Exception as why: print why
db.close()

向我展示了这个错误:

(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '<vCard xmlns='vcard-temp'><VERSION>3.0</VERSION><ADR><HOME/></ADR><ADR><WORK/></' at line 1")

但是当我尝试通过终端连接到mysql并插入它时,它的工作是100%

我在终端做的事情:

mysql -u test1 -p test1

INSERT INTO vcard(username,vcard) VALUES("user1", "<vCard xmlns='vcard-temp'><VERSION>3.0</VERSION><ADR><HOME/></ADR><ADR><WORK/></ADR><TEL><HOME/></TEL><TEL><WORK/></TEL><TEL><FAX/></TEL><TEL><CELL/></TEL><EMAIL><HOME/><USERID>user1@domain.tld</USERID></EMAIL><EMAIL><WORK/></EMAIL><JABBERID></JABBERID><ORG><ORGUNIT/></ORG><PRODID></PRODID></vCard>");

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您不需要将%s放在引号中:

cur.execute("INSERT INTO vcard(username,vcard) VALUES(%s, %s)"%(username, vCard))

您还可以删除值元组前导的%

cur.execute("INSERT INTO vcard(username,vcard) VALUES(%s, %s)",(username, vCard))