2011-10-22 80 views
1

我不明白爲什麼它不起作用。我創建了幾個數據庫和表格,顯然沒有問題。但我堅持這個從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) 

你能指出我的錯嗎?

感謝

+1

您正在捕捉所有異常,因此看不到錯在哪裏。要麼再次拋出異常,要麼至少打印回溯。 – utapyngo

+0

除非有一些真正智能的字符串插值在那裏進行,否則您的查詢將像這樣插入到blah(用戶)值(用戶)這個無效的數據庫中到達DB_literally_。 – Mat

+0

不應該c:\是雙重逃脫? 'c:\'這可能是問題所在? – Serdalis

回答

1
sql = """INSERT INTO pmass_experiment (user,filetype,createddate,uploaddate,time,size,located) 
    VALUES (user, ftype, date, date, time, size, located)""" 

參數多態的SQL,並傳入值作爲第二個參數cursor.execute

sql = """INSERT INTO pmass_experiment (user,filetype,createddate,uploaddate,time,size,located) 
     VALUES (%s, %s, %s, %s, %s, %s, %s)""" 
try: 
    # Execute the SQL command 
    cursor.execute(sql,(user, ftype, date, date, time, size, located)) 
    # Commit your changes in the database 
    conn.commit() 
except Exception as err: 
    # logger.error(err) 
    # Rollback in case there is any error 
    conn.rollback() 

這是一個好習慣,總是參數化的SQL,因爲這將有助於防止sql injection

原來的SQL

INSERT INTO pmass_experiment (user,filetype,createddate,uploaddate,time,size,located) 
    VALUES (user, ftype, date, date, time, size, located) 

似乎是有效的。在mysql殼的實驗表明它插入NULL值行:

mysql> insert into foo (first,last,value) values (first,last,value); 
Query OK, 1 row affected (0.00 sec) 
mysql> select * from foo order by id desc; 
+-----+-------+------+-------+ 
| id | first | last | value | 
+-----+-------+------+-------+ 
| 802 | NULL | NULL | NULL | 
+-----+-------+------+-------+ 
1 row in set (0.00 sec) 

所以我不知道爲什麼你沒有看到提交到數據庫表中的所有行。

儘管如此,原始的sql可能不會做你想要的。

+0

這就是我正在談論的。你能解釋一下我的原始sql是如何導致cursor.execute引發異常的嗎? – thchand

+0

我不是說它不工作。我只想進一步解釋關於sql參數化。但現在很明顯。謝謝:) – thchand

+0

哦,好的。我只是將它們鏈接到這裏以供將來參考:[來自MySQLdb教程的示例](http://mysql-python.sourceforge.net/MySQLdb.html#some-examples)和[PEP 0249:DB-API 2.0](http://www.python.org/dev/peps/pep-0249/) – unutbu