【问题标题】:Cannot insert into MySQL database using MySQLdb python [duplicate]无法使用 MySQLdb python 插入 MySQL 数据库 [重复]
【发布时间】:2018-01-05 14:52:45
【问题描述】:

我一直在尝试使用 MySQLdb 接口从 python 插入 MySQL 数据库。虽然我已经能够成功执行选择查询,但我的插入查询什么也不做。它们不返回错误,但也不向数据库添加任何内容。

我将我的程序简化为这个。

db = MySQLdb.connect(host='127.0.0.1',user=...,passwd=...,db=...)
cursor = db.cursor()
cursor.execute("""INSERT INTO user_event_log (username, major_event_id, minor_event_id, value, date) VALUES ('Test', 1, 1, '0.1', '2017-07-29')""")

不确定我是否犯了一个非常愚蠢的错误,但我无法弄清楚为什么没有插入任何内容。

【问题讨论】:

    标签: python mysql sql


    【解决方案1】:

    您需要在数据库中提交更改并关闭数据库。 请按照以下代码更改:

    import MySQLdb
    
    # Open database connection
    db = MySQLdb.connect(host='127.0.0.1',user=...,passwd=...,db=...)
    
    # prepare a cursor object using cursor() method
    cursor = db.cursor()
    sql = """INSERT INTO user_event_log (username, major_event_id, minor_event_id, value, date) VALUES ('Test', 1, 1, '0.1', '2017-07-29')"""
    try:
       # Execute the SQL command
       cursor.execute(sql)
       # Commit your changes in the database
       db.commit()
    except:
       # Rollback in case there is any error
       db.rollback()
    
    # disconnect from server
    db.close()
    

    【讨论】:

      【解决方案2】:

      您需要将MySQLdb.commit() 添加到您的连接中。 (Source)

      这就像在代码末尾添加db.commit() 一样简单。

      希望对你有帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-08
        • 2013-01-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多