我創建了一個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。
我在做什麼錯?
你試過'mydatum = i.date()'和使用參數化查詢即'cursor.execute(... VALUES(%S, %s,%s,%s)「,(mydatum,mystroom,..))??注意:它不使用字符串格式(%) – jfs 2014-10-18 07:04:54