使用 Python(Windows 身份验证)连接到 SQL Server Express 数据库
Connect to SQL Server Express Database with Python (Windows Authentication)
我有一个 Java 程序连接到我的 SQLServer Express 数据库。我用来连接的代码是:
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] Data source name not found and no default driver specified (0) (SQLDriverConnect)')"
尝试使用这种方法:
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()
我使用以下方法让它工作:
import pyodbc
con = pyodbc.connect(Trusted_Connection='yes', driver = '{SQL Server}',server = 'GANESHA\SQLEXPRESS' , database = '4YP')
我有一个 Java 程序连接到我的 SQLServer Express 数据库。我用来连接的代码是:
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] Data source name not found and no default driver specified (0) (SQLDriverConnect)')"
尝试使用这种方法:
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()
我使用以下方法让它工作:
import pyodbc
con = pyodbc.connect(Trusted_Connection='yes', driver = '{SQL Server}',server = 'GANESHA\SQLEXPRESS' , database = '4YP')