2016-12-27 87 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

完美!现在它正在工作。非常感谢您的帮助! –