Python Pymysql插入不工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20485332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:34:46  来源:igfitidea点击:

Pymysql Insert Into not working

pythonmysqleclipsepython-2.7pymysql

提问by Michael T

I'm running this from PyDev in Eclipse...

我在 Eclipse 中从 PyDev 运行它......

import pymysql
conn = pymysql.connect(host='localhost', port=3306, user='userid', passwd='password', db='fan')
cur = conn.cursor()
print "writing to db"
cur.execute("INSERT INTO cbs_transactions(leagueID) VALUES ('test val')")
print "wrote to db"

The result is, at the top of the Console it says C:...test.py, and in the Console:

结果是,在控制台顶部显示 C:...test.py,在控制台中:

writing to db wrote to db

写入 db 写入 db

So it's not terminating until after the execute command. But when I look in the table in MySQL it's empty. A record did not get inserted.

所以它不会在执行命令之后终止。但是当我查看 MySQL 中的表时,它是空的。没有插入记录。

First off, why isn't it writing the record. Second, how can I see a log or error to see what happened. Usually there should be some kind of error in red if the code fails.

首先,为什么不写记录。其次,如何查看日志或错误以了解发生了什么。如果代码失败,通常应该有某种红色错误。

采纳答案by qmorgan

Did you commit it? conn.commit()

你犯了吗? conn.commit()

回答by Steely Wing

PyMySQL disable autocommitby default, you can add autocommit=Trueto connect():

PyMySQLautocommit默认禁用,您可以添加autocommit=Trueconnect()

conn = pymysql.connect(
    host='localhost',
    user='user',
    passwd='passwd',
    db='db',
    autocommit=True
)

or call conn.commit()after insert

conn.commit()插入后调用

回答by Simeon

You can either do

你可以这样做

  • conn.commit()before calling close
  • conn.commit()打电话之前 close

or

或者

  • enable autocommit via conn.autocommit(True)right after creating the connection object.
  • conn.autocommit(True)在创建连接对象后立即启用自动提交。

Both ways have been suggested from various people at a duplication of the question that can be found here: Database does not update automatically with MySQL and Python

两种方法都被不同的人在重复的问题中提出,可以在这里找到:数据库不会自动更新 MySQL 和 Python