2011-10-22 2 views
1

왜 작동하지 않는지는 알 수 없습니다. 몇 가지 데이터베이스와 테이블을 만들었고 분명히 아무런 문제가 없습니다. 하지만 장고 데이터 모델에서 만든이 테이블에 붙어있다. 내가 한 일을 명확히하기 위해, mysql 콘솔에서 새로운 데이터베이스와 테이블을 생성하고 파이썬에서 삽입하여 작업을 시도한다. 그러나, 이것은 나를 위해 이상합니다. 여기 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> 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 테이블 위 MySQL은 콘솔에서보기를 내가 데이터를 삽입하려고 지금

파이썬 manage.py의 syncdb 후 장고 ORM에 의해 생성된다 python 통해 pmass_experiment에 MySQLdb

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) 

내 실수를 지적 할 수 있습니까?

감사

cursor.execute 두 번째 인수로 값을 전달
+1

모든 예외를 포착하고 있으므로 무엇이 잘못되었는지 알 수 없습니다. 예외를 다시 발생 시키거나 최소한 추적을 출력한다. – utapyngo

+0

정말로 지능적인 문자열 보간법이 없다면, 쿼리는 유효하지 않은 'blah (사용자) 값 (사용자)에 삽입'처럼 DB _ literalally_에 도달합니다. – 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과 :

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> 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) 

그래서 나는 당신의 데이터베이스 테이블에 최선을 다하고 행이 표시되지 않는 이유를 모르겠어요 다음 mysql 셸의 실험은 NULL 값의 행을 삽입 보여줍니다.

그럼에도 불구하고 원래 SQL은 의도 한대로 수행하지 않을 수 있습니다.

+0

그게 내가 말하는거야. 원래 SQL에서 cursor.execute가 expection을 발생시키는 이유를 설명해 주시겠습니까? – 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

관련 문제