我正在尝试使用python 2.5.2执行以下代码。该脚本正在建立连接并创建表,但随后失败并出现以下错误。
脚本
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 :(得分: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')
没有引号,这将与O'Reilly这样的名称一起使用,并有助于防止每个数据库适配器设计的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)
但这是不好的做法。