gpt4 book ai didi

python - 使用 Python 将数据插入 MySQL DB

转载 作者:行者123 更新时间:2023-11-29 18:06:40 25 4
gpt4 key购买 nike

我想使用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()

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

如何解决这个问题

最佳答案

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

connect_db.commit();

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

关于python - 使用 Python 将数据插入 MySQL DB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47768212/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com