【发布时间】:2017-05-11 16:35:01
【问题描述】:
我想在 sql 表中转换日期格式,但我不知道为什么这不起作用:
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() 命令,但它就在那里。
【问题讨论】:
-
如果你需要使用参数来确定你的表应该是什么,那就意味着底层的表设计存在很大问题。
标签: python mysql mysql-connector