13

我是 python 新手。我正在尝试查询 MSSQL 数据库。


import pymssql
conn = pymssql.connect(host='hostname', user='username', password='password', database='dbname')
cursor = conn.cursor()
sql = "select count(*) from T_Email with (nolock) where Transmit is null"
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
  print (row)

成功运行的查询是 Microsoft SQL Server Management Studio,但我的 python 脚本始终没有返回任何内容。

我确认我有网络连接。我验证了用户名、密码和数据库名称。如果我更改密码,那么脚本会出错。

我已经尝试过 results = cursor.fetchone(),但这并没有帮助。

有什么建议么?

4

6 回答 6

4

如果您使用的是 Ubuntu,您可能已经(像我一样)使用 apt-get 来安装 pymssql 包。

这是捆绑版本的一个已知错误:https ://bugs.launchpad.net/ubuntu/+source/pymssql/+bug/918896

尝试使用 easy_install 手动安装。

于 2012-12-29T16:40:01.127 回答
4

我在 Ubuntu 12.04 上遇到了同样的问题,实际上修复是按以下顺序进行的:

$ apt-get purge python-pymssql
$ apt-get install freetds-dev
$ pip install Cython
$ pip install pymssql
于 2013-06-06T20:27:16.817 回答
1

尝试在查询中添加 conn.commit()

于 2011-08-31T00:31:58.030 回答
0

如果没有足够的信息来重现该示例,很难说出您遇到的具体问题。但是,对于可能出现的问题,我有一些猜测:

  1. 也许您的实际列名(假设您上面的示例只是一个模型)太长了。请参阅:http ://code.google.com/p/pymssql/wiki/FAQ (查找 Column names get quietly truncated to 30 characters.(1.x only))这是一个常见的绊倒人,因为它默默地失败!!
  2. 如果您在查询表之前创建表,或者其他需要提交的事情,它可能会搞砸,即使打开了自动提交 ( autocommit(1))。在 pymssql ( python 模块 ) 上查看我对自己的回答无法使用临时表

祝你好运!

麦克风

于 2012-01-13T01:01:22.037 回答
0

更改代码段中的以下行

results = cursor.fetchall()
for row in results:
  print (row)

进入

# results = cursor.fetchall()
for row in cursor:
  print (row)

pymssql 在cursor.fetchall()中有错误

供参考https://github.com/pymssql/pymssql/issues/141

于 2018-05-18T08:44:29.513 回答
0
import pymssql

conn = pymssql.connect(
server="server",
port=port,
user="user",
password=password,
database="database")
conn

cursor = conn.cursor()
cursor.execute("select count(*) from T_Email with (nolock) where Transmit is null")
     for row in cursor.fetchall():  
     print ("%s\n" % str(row))
conn.close()
于 2018-04-28T15:55:15.083 回答