【问题标题】:Inserting data into MySQL DB using Python [duplicate]使用 Python 将数据插入 MySQL DB [重复]
【发布时间】:2017-12-12 08:32:44
【问题描述】:

我想使用 python 将数据插入 Mysql 数据库。这是我的代码

def insert_db(time_spent):
global user_id
global total_time_spent
user = user_id
project = get_project_id()
timesingle = time_spent
timeall = total_time_spent
#connect to the database
connect_db = mysql.connector.connect(user='root',password='',host='127.0.0.1',database='python_test')
cursor = connect_db.cursor()
cursor.execute("INSERT INTO time (user_id,project_id,spent_time,total_time) VALUES (%s,%s,%s,%s)",(user,project,timesingle,timeall)) # insert new row to table
if cursor.lastrowid:
    print('last insert id', cursor.lastrowid)
else:
    print('last insert id not found')
#close the cursor and database connection
cursor.close()
connect_db.close()

问题是当我执行这个函数时,即使'last insert row id'显示的是id,数据也没有插入到数据库中。我检查了这个函数中的所有变量,它们都不为空。

我该如何解决这个问题

【问题讨论】:

标签: python mysql


【解决方案1】:

每次修改数据库中的数据时,都需要提交所有更改。

connect_db.commit();

这是为了确保您只保存未发生错误的更改。

【讨论】:

    【解决方案2】:

    您需要提交以标记成功事务的结束。

    connect_db.commit()
    

    更多信息:https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html

    【讨论】:

      【解决方案3】:

      请确保在每次插入/更新或其他此类语句后使用connect_db.commit()

      【讨论】:

        猜你喜欢
        • 2016-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多