2013-12-21 23 views
0

我在Python中使用MySQLdb模塊來創建表,但在嘗試使用datetime模塊命名它時遇到了一些問題。MySQLdb - 在Python中使用datetime模塊命名錶

class DbPipeline(object): 
def __init__(self): 
    vendor = "vendorname" 
    curDate = time.strftime('%Y-%m-%d').replace("-", ".") 
    tableName = vendor + ":" + curDate 

    # connect to the database 
    self.conn = MySQLdb.connect(host='127.0.0.1', user='root', passwd='', db='dbname', charset="utf8", use_unicode=True) 
    self.cursor = self.conn.cursor() 

    #create a new table 
    sql = "CREATE TABLE %s (name CHAR(40))" %tableName 
    self.cursor.execute(sql) 

這將導致以下錯誤: 「養errorclass,errorvalue _mysql_exceptions.ProgrammingError:(1064,」您的SQL語法錯誤;檢查對應於你的MySQL服務器版本的手冊對於在第1行':2013.12.21(name CHAR(40))'附近使用正確的語法「)

我很確定這可能是與字符轉義或我的sql查詢的方式定義,但大量的谷歌和REPL會議後,我還沒有設法解決它。

從REPL一些代碼:

vendor = "vendorname" 
curDate = time.strftime('%Y-%m-%d').replace("-", ".") 
tableName = vendor + ":" + curDate 
sql = "CREATE TABLE %s (name CHAR(40))" %tableName 
sql 
'CREATE TABLE vendorname:2013.12.21 (name CHAR(40))' 

最後稍微注意一下,如果你是剛分配%的表名A-Z字這個完美的作品。感謝您的閱讀和道歉,如果這是一件非常明顯的事我錯過了!

+0

爲什麼'time.strftime( '%Y-%間 - %d')。替換(「 - 」,「。」)'不是'time.strftime('%Y.%m。%d')'? – jonrsharpe

+0

我最初使用datetime.now()。date()然後將它轉換爲一個字符串,但是一個SO post使用了time.strftime('%Y-%m-%d'),它似乎是一個更好的做事方式。 – Toby

+0

您可以更改格式字符串以提供所需的格式,而不需要任何「替換」:http://docs.python.org/2/library/time.html#time.strftime – jonrsharpe

回答

1

按照MySQL documentation

Database and table names cannot contain 「/」, 「\」, 「.」, or characters that are not permitted in file names.

嘗試:

curDate = time.strftime('%Y%m%d') 
tableName = "%s_%s" % (vendor, curDate) 

例如,"vendorname_20131221"

+0

我試圖完全刪除這些字符,但仍然有同樣的問題。我會再給它一次! – Toby

+0

美麗,做到了!謝謝你:D !.看起來我需要閱讀更多關於字符串的內容! – Toby

相關問題