0

我正在尝试使用 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

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

4

1 回答 1

1

我认为您正在假设常规的 python 字符串插值行为,即:

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

execute 方法中的%操作符看起来像普通的字符串格式化操作符,但更多的是方便或助记符;您的代码应为:

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)

但这是不好的做法。

于 2010-12-01T13:09:26.697 回答