【问题标题】:Python MySQLdb Insert fails on MariaDB: Doesn't persist to new connectionMariaDB上的Python MySQLdb插入失败:不会持续到新连接
【发布时间】:2016-08-22 03:28:47
【问题描述】:

以下代码中的 assert 语句在运行 mariadb 的环境中失败,而在运行 mysql 的(旧)环境中运行良好。 mariadb 环境似乎没有保留插入语句的结果。与命令行客户端连接确认插入未持久化。

import MySQLdb

def newCon():
    return MySQLdb.connect('localhost', 'root', '', 'test')

def testStatement(con, aStatement):
    # print "---"
    # print aStatement
    cur = con.cursor()
    cur.execute(aStatement)
    result = cur.fetchall()
    cur.close()
    # print result
    return result

def test():
    con = newCon()

    testStatement(con, "DROP TABLE IF EXISTS TestTable")
    testStatement(con, """CREATE TABLE TestTable (
            id INT NOT NULL AUTO_INCREMENT,
            AccountId VARCHAR(50),
            PRIMARY KEY(id))""")
    testStatement(con, "INSERT INTO TestTable (AccountId) VALUES ('XYZ')")
    myCount1 = testStatement(con, "SELECT count(*) from TestTable")[0][0]

    con.close()
    con = newCon()

    myCount2 = testStatement(con, "SELECT count(*) from TestTable")[0][0]

    con.close()

    assert myCount1 == myCount2, \
      "count1 = " + str(myCount1) + " != count2 = " + str(myCount2)

test()

它运行良好的环境是: CentOS 6.7 蟒蛇2.6.6 mysql-python 1.2.3 mysql服务器5.1.73

失败的环境是: 软呢帽 21 蟒蛇2.7.8 mysql-python 1.2.3 mariadb 服务器 10.0.21

失败的输出内容为:

Test2.py:10: Warning: Table 'mysql.table_stats' doesn't exist
  cur.execute(aStatement)
Traceback (most recent call last):
  File "Test2.py", line 37, in <module>
    test()
  File "Test2.py", line 35, in test
    "count1 = " + str(myCount1) + " != count2 = " + str(myCount2)
AssertionError: count1 = 1 != count2 = 0

我不知道 table_stats 警告是关于什么的。

问题:我是否正确使用了 api?任何人都可以使用 mariadb 环境通过此测试吗?

【问题讨论】:

    标签: python mariadb mysql-python


    【解决方案1】:

    你还没有提交交易。

    【讨论】:

    • 如何提交事务?这是 mariadb 特有的,还是我也应该用 mysql 来做?
    • 谢谢,成功了!用 BEGIN - COMMIT 包围 INSERT
    • 如果autocommit 已开启,则问题不会存在。我想知道为什么它关闭了。见stackoverflow.com/questions/12059424/…
    • autocommit=off 是 Python 的愚蠢默认设置。
    猜你喜欢
    • 2023-03-26
    • 2013-09-12
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 2021-05-17
    相关资源
    最近更新 更多