2016-12-27 92 views
0

我想日期格式轉換成SQL表,我不知道爲什麼這不工作:mysql.connector爲蟒蛇的commit()不工作

import mysql.connector 
from mysql.connector import errorcode 
from dateutil.parser import parse 

appname = "dropbox" 

# connect to the database 
# Add your DB connection information 

try: 

    database = mysql.connector.connect(user='root', password='root', 

           host='localhost', 

           database='google_play') 

except mysql.connector.Error as err: 

    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: 
     print("Something is wrong with your user name or password") 

    elif err.errno == errorcode.ER_BAD_DB_ERROR: 
     print("Database does not exist") 

    else: 
     print(err) 

DBcursor = database.cursor(buffered=True) 
DBcursor2 = database.cursor(buffered=True) 

# DB connection established. Now get the table: 

query = ("SELECT * FROM googleplay_%s_test" % appname) 

DBcursor.execute(query) 

# Execute the date conversion: 

for (id, user_name, date, url, rating, title, text, reply_date, reply_text) in DBcursor: 

    date_string = parse(date) 
    date_string.strftime("%Y-%m-%d") 

    conversion = ("UPDATE googleplay_%s_test SET date='date_string' WHERE id='id'" % appname) 

    DBcursor2.execute(conversion) 

    database.commit() 

    print("Convertet to: ", date_string) 

# close the database connection 

DBcursor.close() 
DBcursor2.close() 
database.close() 

轉換似乎工作。輸出是:

Convertet to: 2016-12-02 00:00:00 
Convertet to: 2016-11-25 00:00:00 
Convertet to: 2016-11-16 00:00:00 
Convertet to: 2016-12-04 00:00:00 

這很好。但是,它不會將新值寫入表中。首先,我想到commit()命令丟失,但它在那裏。

+0

如果您需要使用參數來確定您的表應該是什麼,這意味着底層表設計中存在一個大問題。 – e4c5

回答

0

這樣的:

conversion = ("UPDATE googleplay_%s_test SET date='date_string' WHERE id='id'" % appname) 
DBcursor2.execute(conversion) 

顯然是不打算設置googleplay_<whatever>_testdate_string變量的值 - 它會嘗試將其設置爲litteral 'date_string'字符串。很可能MySQL只是默默地跳過操作(嗯,可能最好發出一個警告),並假裝一切正常,通常使用默認的MySQL設置。

編輯:同樣適用於where條款:

WHERE id='id' 

將只嘗試更新記錄哪個ID是litteral串'id'

你想:

conversion = "UPDATE googleplay_%s_test SET date=%%s WHERE id=%%s" % appname 
DBcursor2.execute(conversion, [date_string, id]) 

FWIW,如果你只需要兩個字段,你最好檢索只有兩個字段:

query = "SELECT id, date FROM googleplay_%s_test" % appname 
DBcursor.execute(query) 

for id, date in DBcursor: 
    # code here 

,雖然我們是在它:

  1. cursor.execute()返回查詢所影響的行數(選擇,更新,刪除,無論)
  2. 您可能希望將database.commit()置於循環之外 - 單個提交的速度更快,並且可以確保所有更改都已應用或沒有更改,這可避免將數據庫置於半支持狀態。

另外請注意,你傳遞什麼作爲date_string這裏其實並不是一個字符串,但一個datetime.datetime對象,因爲你放棄呼叫date_string.strftime()的結果。但這應該沒問題,dbapi連接器應該知道如何在db和python類型之間進行轉換。

最後:一個合適的數據庫模式將有一個googleplay_test表和appname作爲一個字段。

+0

感謝您的幫助。不幸的是,這並沒有太大的改變。它仍然不會將新值寫入表中。 –

+0

你在where子句中有同樣的問題,請參閱我的編輯。你可以從我的答案FWIW中發現它... –

+0

完美!現在它正在工作。非常感謝您的幫助! –