2017-12-12 15 views
0

Pythonを使用してMysqlデータベースにデータを挿入したいとします。ここでの問題は、私はこの機能も「最後の挿入行のIDが」IDを示しているを実行すると、データがデータベースに挿入されていないです私のコードPythonを使用してMySQL DBにデータを挿入

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() 

です。私はこの関数のすべての変数をチェックし、空ではありません。

は、どのように私はあなたが持つすべての変更をコミットする必要がありますが、データベース内のデータを修正し、この問題に

+0

あなたはコミットするのを忘れました。 –

+0

ありがとう!固定されています – user7592296

+0

関連https://stackoverflow.com/questions/9173073/why-isnt-the-insert-function-adding-rows-using-mysqldb –

答えて

0

毎回を修正することができます。

connect_db.commit(); 

これは、エラーが発生していない場合にのみ変更を保存するためです。

0

あなたはすべての挿入/更新または他のそのような文の後connect_db.commit()を使用していることを確認してください。

関連する問題