2010-12-01 21 views
0

我试图用python 2.5.2来执行下面的代码。该脚本正在建立连接并创建表,但随后出现以下错误。python的引用错误 - 使用pymssql

脚本

import pymssql 
conn = pymssql.connect(host='10.103.8.75', user='mo', password='the_password', database='SR_WF_MODEL') 
cur = conn.cursor() 
cur.execute('CREATE TABLE persons(id INT, name VARCHAR(100))') 
cur.executemany("INSERT INTO persons VALUES(%d, %s)", \ 
    [ (1, 'John Doe'), (2, 'Jane Doe') ]) 
conn.commit() 

cur.execute("SELECT * FROM persons WHERE salesrep='%s'", 'John Doe') 
row = cur.fetchone() 
while row: 
    print "ID=%d, Name=%s" % (row[0], row[1]) 
    row = cur.fetchone() 

cur.execute("SELECT * FROM persons WHERE salesrep LIKE 'J%'") 

conn.close() 

错误

Traceback (most recent call last): 
    File "connect_to_mssql.py", line 9, in <module> 
    cur.execute("SELECT * FROM persons WHERE salesrep='%s'", 'John Doe') 
    File "/var/lib/python-support/python2.5/pymssql.py", line 126, in execute 
    self.executemany(operation, (params,)) 
    File "/var/lib/python-support/python2.5/pymssql.py", line 152, in executemany 
    raise DatabaseError, "internal error: %s" % self.__source.errmsg() 
pymssql.DatabaseError: internal error: None 

有什么建议?另外,你如何阅读回溯错误,任何人都可以帮助我理解错误信息?你怎么读它?自下而上?

+0

这个回溯是一个坏玩笑。如果错误是“无”,那么它为什么抱怨?是的,回溯从下往上读取。每条线都是调用其下方线条的线。 – aaronasterling 2010-12-01 11:59:06

回答

1

我想你是假设常规的Python字符串插值行为,即:

>>> a = "we should never do '%s' when working with dbs" 
>>> a % 'this' 
"we should never do 'this' when working with dbs" 

内执行方法貌似正常的字符串格式化操作,但是这更多的是方便或记忆的%操作;您的代码应阅读:

cur.execute("SELECT * FROM persons WHERE salesrep=%s", 'John Doe')

不带引号,这将与像奥赖利名工作,并有助于防止每个数据库适配器设计SQL注入。这实际上就是数据库适配器的用途 - 将python对象转换为sql;它会知道如何引用一个字符串,并正确逃生标点符号等,如果你没有它的工作:

>>> THING_ONE_SHOULD_NEVER_DO = "select * from table where cond = '%s'" 
>>> query = THING_ONE_SHOULD_NEVER_DO % 'john doe' 
>>> query 
"select * from table where cond = 'john doe'" 
>>> cur.execute(query) 

但是这是不好的做法。