mysql 更新数据无效_python mysql 更新和插入数据无效

Python操作MySQL时,由于使用事务处理,更新或插入数据必须提交(commit)才能生效。若未调用commit,数据将无法在其他连接中可见。官方文档示例代码展示了如何创建表、插入数据并提交事务。注意,MySQLdb库遵循通用的数据库接口标准,因此只需展示一个样例即可。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

无效原因 在 这里 中文原因, 在 官网 上也找到英文原因了,简单的说就是 python 操作mysql 是用 事物的方式来实现的,所以在update 或 insert 的时候 必须有commit 提交的过程,否则数据表不会生效; This method commits the current transaction. If you d

无效原因

在 这里 中文原因, 在 官网 上也找到英文原因了,简单的说就是

python 操作mysql 是用 事物的方式来实现的,所以在update 或 insert 的时候 必须有commit 提交的过程,否则数据表不会生效;

This method commits the current transaction.

If you don’t call this method, anything you did since the last call to commit() is not visible from other database connections.

If you wonder why you don’t see the data you’ve written to the database, please check you didn’t forget to call this method.

简单的说就是执行修改数据库的操作后,需要提交,才会确认执行。

文档的一个问题

如果你点开我的那个官方文档的话,会发现这个不是 mysql 的文档,而是 sqlite3 的文档。

因为在官方文档 没有 mysql 的文档,至少 2014-10-20 19:28:00 这个时候没有。

样例代码

直接 copy 官网的样例代码了。

import MySQLdb

dbcfg = {'host' : '127.0.0.1', 'port' : 3306, 'user' : 'test', 'passwd' : 'test', 'db' : 'test'}

try:

conn = MySQLdb.connect(host=dbcfg["host"], user=dbcfg["user"], passwd=dbcfg["passwd"], db=dbcfg["db"], port=dbcfg["port"], charset='utf8')

cur = conn.cursor()

# Create table

cur.execute("CREATE TABLE test(date text, trans text, symbol text, qty real, price real)")

# Insert a row of data

cur.execute("INSERT INTO test VALUES ('2006-01-05','BUY','RHAT',100,35.14)")

## Never do this -- insecure!

symbol = 'RHAT'

# escape string

symbol = conn.escape_string(symbol)

# select

c.execute("SELECT * FROM test WHERE symbol = '%s'" % symbol)

# Save (commit) the changes

conn.commit()

# We can also close the connection if we are done with it.

# Just be sure any changes have been committed or they will be lost.

conn.close()

except MySQLdb.Error,e:

print("Mysql Error %d: %s" % (e.args[0], e.args[1]))

官方资料

后来发现,之所以官方没有 mysql 的文档,是因为官方制定了数据库操作的标准.

所有的数据库都按照这个标准提供接口的,所以只需要提供一个样例接口就行了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值