使用Python连接SQL Server Express数据库(Windows身份验证)

8

我有一个连接到SQLServer Express数据库的Java程序。我使用的连接代码是:

Connection con = null;
try {   
    String url = "jdbc:sqlserver://GANESHA\\SQLEXPRESS:1434;databaseName=4YP;integratedSecurity=true";
    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    con = DriverManager.getConnection(url);
}

我已经决定改用Python来编写代码,但是似乎无法与我的数据库建立连接。我一直在使用以下代码:

import pyodbc

con_str = (
    r'Driver = {SQL SERVER};'
    r'Server = .\GANESHA;'
    r'Database = 4YP;'
    r'TrustedConnection = yes;'
)
cnxn = pyodbc.connect(con_str)

我收到的错误是:"pyodbc.Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] 数据源名称未找到且未指定默认驱动程序 (0) (SQLDriverConnect)')。"
2个回答

9
我使用以下方法使它正常工作:
import pyodbc

con = pyodbc.connect(Trusted_Connection='yes', driver = '{SQL Server}',server = 'GANESHA\SQLEXPRESS' , database = '4YP')

这也是我做的方式。 - Neo

2

尝试使用这种方法:

import pyodbc
cnxn = pyodbc.connect(r'Driver={SQL Server};Server=myServer;Database=myDB;Trusted_Connection=yes;')
cursor = cnxn.cursor()
cursor.execute("SELECT * FROM myTable")
while 1:
    row = cursor.fetchone()
    if not row:
        break
    print(row.myColumnName)
cnxn.close()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接