Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect to SQL Server Express Database with Python (Windows Authentication)

I've got a Java Program connected to my SQLServer Express Database. The code I used to connect is:

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);
}

I have since decided to use Python instead but can't seem to get it to connect to my database. The code I've been using is:

import pyodbc

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

The error I'm getting is: "pyodbc.Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')"

like image 811
Aine Avatar asked Dec 01 '16 14:12

Aine


People also ask

How do I log into SQL Server with Windows authentication?

Open SQL Server Management Studio. In Connect to Server, select Database Engine, enter your SQL Server name, and enter administrator credentials to connect to the server. Select Connect. In Object Explorer, expand the SQL Server, expand Security, right-click Logins, and then select New Login.

Does SQL database support Windows integrated authentication?

To connect to SQL Server using Windows integrated authentication, you must identify the Windows identity under which your ASP.NET application is running. You must also be sure that the identity has been granted access to the SQL Server database.


1 Answers

I got it to work using the following approach:

import pyodbc

con = pyodbc.connect(Trusted_Connection='yes', driver = '{SQL Server}',server = 'GANESHA\SQLEXPRESS' , database = '4YP')
like image 194
Aine Avatar answered Oct 05 '22 23:10

Aine