【问题标题】:Echo pyodbc output in php script in Ubuntu 14.04在 Ubuntu 14.04 的 php 脚本中回显 pyodbc 输出
【发布时间】:2015-07-08 21:27:13
【问题描述】:

我有一台运行本地服务器的 Ubuntu 14.04 机器。

在这台服务器上,我有一个 PHP 脚本需要访问远程 Microsoft Azure SQL 数据库上的数据。

我无法找到使用纯 PHP 从 Ubuntu 访问数据库的方法,因此我尝试了 Python 脚本并在遵循本教程后导入了 pyodbc 库:https://snakeycode.wordpress.com/2013/12/04/installing-pyodbc-on-ubuntu-12-04-64-bit/

我可以从终端运行此脚本,它成功连接到 Azure SQL 数据库并将我的查询输出打印到控制台。

这是个好消息,所以我开始在本地服务器上进行测试。


在服务器上,在 PHP 方法中,我调用 echo shell_exec('my_script.py');

这给了我一个错误:

pyodbc.Error: ('08001', '[08001] [unixODBC][FreeTDS][SQL Server]
Unable to connect to data source (0) (SQLDriverConnect)')

为什么my_script.py在本地服务器执行时不起作用?

【问题讨论】:

  • 是否可以直接在 PHP 中使用 Microsoft Sql Server ODBC Driver for Linux?见stackoverflow.com/questions/20163776/…
  • 当您从终端成功运行时,是在您描述为“本地服务器”的同一台机器上吗?您可能希望直接从 PHP 连接,您可以使用相同的 FreeTDS 和 unixODBC 底层堆栈来实现。您是否从“本地服务器”的命令行尝试过 tsql 和 isql?

标签: php python ubuntu azure pyodbc


【解决方案1】:

将 TDS 版本用作 8.0,并在您的 pyodbc.connect 连接字符串中提及。

示例代码:

#!/usr/bin/python
"Proof connection at pyodbc level."
# Test pyodbc connection.

import pyodbc

conn = pyodbc.connect('DRIVER=FreeTDS;DSN=mssql;UID=userid@servername.database.windows.net;PWD=xxxxxxxx;TDS_Version=8.0;')
cursor = conn.cursor()
cursor.execute("SELECT * FROM sys.tables")
print( cursor.fetchall() )
conn.close()

内容:/etc/freetds/freetds.conf:

[global]
        # TDS protocol version
        tds version = 8.0

        # Whether to write a TDSDUMP file for diagnostic purposes
        # (setting this to /tmp is insecure on a multi-user system)
        dump file = /tmp/freetds.log
        debug flags = 0xffff

        # Command and connection timeouts
;       timeout = 10
;       connect timeout = 10

        # If you get out-of-memory errors, it may mean that your client
        # is trying to allocate a huge buffer for a TEXT field.
        # Try setting 'text size' to a more reasonable limit
        text size = 64512

# A typical Sybase server
#[egServer50]
#       host = symachine.domain.com
#       port = 5000
#       tds version = 5.0

# A typical Microsoft server
[mssql]
        host = servername.database.windows.net
        port = 1433
        tds version = 8.0

/etc/odbc.ini 文件内容:

[mssql]
Driver = FreeTDS
Description = ODBC connection via FreeTDS
Trace = Yes
ServerName = mssql
Database = databasename
TDS_Version = 8.0

/etc/odbcinst.ini 文件内容:

[FreeTDS]
Description=FreeTDS Driver
Driver=/usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup=/usr/lib/x86_64-linux-gnu/odbc/libtdsS.so

如果您仍然无法访问,请告知我们并提供您遇到的确切错误。

另外一个重要的步骤是将运行此代码的 IP 地址添加到 sql azure 数据库的防火墙规则中。

【讨论】:

  • 在 /etc/freetds/freetds.conf 中,我启用了 tds 日志,但您可以在测试连接后禁用它。
猜你喜欢
  • 2022-01-20
  • 1970-01-01
  • 2017-02-11
  • 2015-02-19
  • 1970-01-01
  • 2015-10-13
  • 1970-01-01
  • 1970-01-01
  • 2011-11-26
相关资源
最近更新 更多