2014-10-18 97 views
0

我創建了一個MySQL數據庫以L列「日期」:日期插入從蟒蛇到MySQL「超出範圍」的問題

+--------+---------+------+-----+---------+-------+ 
| Field | Type | Null | Key | Default | Extra | 
+--------+---------+------+-----+---------+-------+ 
| datum | date | YES |  | NULL |  | 
| stroom | int(15) | YES |  | NULL |  | 
| gas | int(15) | YES |  | NULL |  | 
| water | int(15) | YES |  | NULL |  | 
+--------+---------+------+-----+---------+-------+ 

然而,當我嘗試從一個Python腳本插入日期它回報: 警告:超出範圍值的列「基準」第1行

我的劇本是這樣的:

#!/usr/bin/python 
import datetime 
import MySQLdb 


# define strings 
i = datetime.datetime.now() 
mydatum = ("%s-%s-%s" % (i.day, i.month, i.year)) 
#mydatum = time.strftime("%Y-%m-%d") 
mystroom = open('/home/pi/textfiles/stroomverbruik.txt', 'r').read(4) 
mygas = open('/home/pi/textfiles/gasverbruik.txt', 'r').read(4) 
mywater = open('/home/pi/textfiles/waterverbruik.txt', 'r').read(4) 


# Open database connection 
db = MySQLdb.connect("localhost","root","[password]","P1") 

# prepare a cursor object using cursor() method 
cursor = db.cursor() 

# Prepare SQL query to INSERT a record into the database. 
sql = "INSERT INTO verbruik (datum, stroom, gas, water) VALUES(%s,%s,%s,%s)" % (mydatum, mystroom, mygas, mywater) 


try: 
    # Execute the SQL command 
    cursor.execute(sql) 
    # Commit your changes in the database 
    db.commit() 
except: 
    # Rollback in case there is any error 
    db.rollback() 

# disconnect from server 
db.close() 


print mydatum 
print mystroom 
print mygas 
print mywater 

是MySQL的期待另一個日期格式? 其他值正確存儲在數據庫中,但日期值存儲爲像0000-00-00。
我在做什麼錯?

+0

你試過'mydatum = i.date()'和使用參數化查詢即'cursor.execute(... VALUES(%S, %s,%s,%s)「,(mydatum,mystroom,..))??注意:它不使用字符串格式(%) – jfs 2014-10-18 07:04:54

回答

0

看起來像Python代碼沒有被付諸D-M-Y代替Y-M-D格式格式正確日期...

嘗試改變

mydatum = ("%s-%s-%s" % (i.day, i.month, i.year)) 

mydatum = ("%s-%s-%s" % (i.year, i.month, i.day)) 

在Python代碼中。

編輯,以反映的意見得出的解決方案:

%s不得不被引用爲好,因爲這個數據庫的日期被告知來處理它作爲一個字符串。修改後的行:

sql =「INSERT INTO verbruik(datum,stroom,gas,water)VALUES('%s',%s,%s,%s)」%(mydatum,mystroom,mygas,mywater)

+0

Thanx,但我試過了所有可能的組合,並且它一直給我超出範圍的警告... – Yos 2014-10-18 06:47:56

+0

@Yos哦!我想我知道發生了什麼事情,試着在查詢字符串中引用'%s'作爲日期,就像這樣:'INSERT INTO verbruik(datum,stroom,gas,水)VALUES('%s',%s,%s,%s)'(注意第一個'%s'周圍的單引號。 – Ruslan 2014-10-18 06:50:37

+0

Thanx!那是爲什麼它需要這些引號? – Yos 2014-10-18 06:55:10

0

將第一個%s放在單引號中是Ruslan發佈的解決方案。 這樣的日期被正確存儲在數據庫中後:

| 0000-00-00 | 2953 | 1021 | 197 | 
| 0000-00-00 | 2953 | 1021 | 197 | 
| 0000-00-00 | 2953 | 1021 | 197 | 
| 2014-10-18 | 2953 | 1021 | 197 | 
+------------+--------+-------+-------+ 
347 rows in set (0.01 sec)