简体   繁体   English

通过MySQLdb用Python插入Mysql数据库

[英]Mysql Database Insert with Python via MySQLdb

This is super basic, but I cannot seem to get it to work correctly, most of the querying I've done in python has been with the django orm . 这是超级基础,但是我似乎无法使其正常工作,我在python中所做的大部分查询都是通过django orm

This time I'm just looking to do a simple insert of data with python MySQLdb , I currently have: 这次我只是想用python MySQLdb简单地插入数据,我目前有:

phone_number = toasted_tree.xpath('//b/text()')

try:
    #the query to execute.
    connector.execute("""INSERT INTO mydbtable(phone_number) VALUES(%s) """,(phone_number))
    conn.commit()
    print 'success!'
except:
    conn.rollback()
    print 'failure'
conn.close()

The issue is, it keeps hitting the except block. 问题是,它一直击中except块。 I've triple-checked my connection settings to mysql and did a fake query directly against mysql like: INSERT INTO mydbtable(phone_number) VALUES(1112223333); and it works fine. 我已经三重检查了与mysql的连接设置,并直接针对mysql进行了伪造查询,例如: INSERT INTO mydbtable(phone_number) VALUES(1112223333); and it works fine. INSERT INTO mydbtable(phone_number) VALUES(1112223333); and it works fine.

Is my syntax above wrong? 我上面的语法错误吗?

Thank you 谢谢

We can't tell what the problem is, because your except block is catching and swallowing all exceptions. 我们无法确定问题出在哪里,因为您的except块正在捕获并吞噬所有异常。 Don't do that. 不要那样做

Remove the try/except and let Python report what the problem is. 删除try / except并让Python报告问题所在。 Then, if it's something you can deal with, catch that specific exception and add code to do so. 然后,如果可以解决,请捕获该特定异常并添加代码来实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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