我不明白爲什麼它不起作用。我創建了幾個數據庫和表格,顯然沒有問題。但我堅持這個從django數據模型創建的表。爲了闡明我所做的,從mysql控制檯創建了新的數據庫和表,並嘗試從python插入並工作。但是,這對我來說很奇怪。MySQL Python插入奇怪?
class Experiment(models.Model):
user = models.CharField(max_length=25)
filetype = models.CharField(max_length=10)
createddate= models.DateField()
uploaddate = models.DateField()
time = models.CharField(max_length=20)
size = models.CharField(max_length=20)
located= models.CharField(max_length=50)
這是鑑於在MySQL控制檯
mysql> describe pmass_experiment;
+-------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| user | varchar(25) | NO | | NULL | |
| filetype | varchar(10) | NO | | NULL | |
| createddate | date | NO | | NULL | |
| uploaddate | date | NO | | NULL | |
| time | varchar(20) | NO | | NULL | |
| size | varchar(20) | NO | | NULL | |
| located | varchar(50) | NO | | NULL | |
+-------------+-------------+------+-----+---------+----------------+
8 rows in set (0.01 sec)
以上pmass_experiment表由Django的ORM後蟒蛇manage.py執行syncdb
現在我想插入數據創建通過python MySQLdb進入pmass_experiment
import MySQLdb
import datetime,time
import sys
conn = MySQLdb.connect(
host="localhost",
user="root",
passwd="root",
db="experiment")
cursor = conn.cursor()
user='tchand'
ftype='mzml'
size='10MB'
located='c:\'
date= datetime.date.today()
time = str(datetime.datetime.now())[10:19]
#Insert into database
sql = """INSERT INTO pmass_experiment (user,filetype,createddate,uploaddate,time,size,located)
VALUES (user, ftype, date, date, time, size, located)"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
conn.commit()
except:
# Rollback in case there is any error
conn.rollback()
# disconnect from server
conn.close()
但是,不幸的是沒有插入。我猜這可能是由於primary_key(id)在表中不自動遞增。
mysql> select * from pmass_experiment;
Empty set (0.00 sec)
你能指出我的錯嗎?
感謝
您正在捕捉所有異常,因此看不到錯在哪裏。要麼再次拋出異常,要麼至少打印回溯。 – utapyngo
除非有一些真正智能的字符串插值在那裏進行,否則您的查詢將像這樣插入到blah(用戶)值(用戶)這個無效的數據庫中到達DB_literally_。 – Mat
不應該c:\是雙重逃脫? 'c:\'這可能是問題所在? – Serdalis