Connect to mssql from python - python

I am trying to connect mssql from python. For this I am using below code but looks like something is wrong with the connection. Can anyone help me ?
import sqlalchemy as sal
from sqlalchemy import create_engine
import pyodbc
##conn = pyodbc.connect('Driver={SQL Server Native client 11.0};server=localhost;database=Nifty;trusted_connection=yes;')
engine = sal.create_engine('mssql+pyodbc://localhost/Nifty?driver=SQL+Server+Native+client+11.0?Trusted_Connection=yes')
engine.execute('select top 2 * from [dbo].ABC')
I am getting below error
InterfaceError: (pyodbc.InterfaceError) ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
(Background on this error at: https://sqlalche.me/e/14/rvf5)

pls first check if you have specified driver in connection:
control panel>Systems and Security>Administrative Tools.>ODBC Data Sources>System DSN tab>Add
and then try :
engine = sal.create_engine('mssql+pyodbc://localhost/Nifty?driver=SQL+Server+Native+client+11.0?Trusted_Connection=yes',echo = True)
official docs
or, You can use some of the Solutions below:
Solution 1
define driver like this :
Driver={ODBC Driver 17 for SQL Server};Server=serverName\instanceName;Database=myDataBase;Trusted_Connection=yes;
and then put it in pyodbc.connect(" here ") and run it using cursor, see this
Solution 2
With Windows Authentication Without using DSN's
engine = sal.create_engine('mssql+pyodbc://server/db')
Solution 3
using urllib
import urllib
params = urllib.parse.quote_plus("DRIVER={SQL Server Native Client 11.0};"
"SERVER=dagger;"
"DATABASE=test;"
"Trusted_Connection=yes")
engine = sa.create_engine("mssql+pyodbc:///?odbc_connect={}".format(params))

Related

I'm trying to connect to a SQL Express Server on my machine using sqlalchemy but I'm getting an error

I'm trying to connect to a SQL Express Server on my machine using sqlalchemy but I'm getting an error. Here is the code I have:
import sqlalchemy as sal
import pandas as pd
sqlcon=sal.create_engine('mssql+pyodbc://#' + 'DESKTOP-A1BUCDR\SQLEXPRESS' + '/' + 'Northwind' + '?driver=ODBC+Driver+13+for+SQL+Server')
df = pd.read_sql_query('select * from Orders', sqlcon)
And here is the error I'm getting:
InterfaceError: (pyodbc.InterfaceError) ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
(Background on this error at: https://sqlalche.me/e/14/rvf5)
Does anyone have any ideas on what I may be getting wrong here?
Your URL evaluates to:
mssql+pyodbc://#DESKTOP-A1BUCDR\\SQLEXPRESS/Northwind?driver=ODBC+Driver+13
+for+SQL+Server
The errors points to not finding the data source name (DSN), which I think you must not want to use since you give what looks like a hostname and a driver parameter.
That's fine too:
mssql+pyodbc://<UID>:<PWD>#DESKTOP-A1BUCDR:1433/Northwind?driver=ODBC+Driver+17+for+SQL+Server
If your port is the default (1433), you don’t really need to add it.
Why is your hostname DESKTOP-A1BUCDR\SQLEXPRESS ? and why are you using ODBC Driver 13 for SQL Server and not a more recent version ?
You could instead try using a URL built for your hostname or directly the pyODBC string.

Pandas sqlalchemy create_engine connection with SQL server windows authentication

I am trying to upload a Pandas DataFrame to SQL server table. From reading, the sqlalchemy to_sql method seems like a great option. However, I am not able to get the create_engine to make the connection.
I am able to connect to the database to retrieve data with Windows authentication. Here is the connection string I am using:
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
"Server={server_name};"
"Database={database_name};"
"Trusted_Connection=yes;")
I have tried several different ways to use my login information to connect, here is the most recent version:
engine = create_engine(
"mssql+pyodbc://{network_user_name}:{network_pw}#{server_name}//{database_name}"
)
engine.connect()
Here is the error I am getting:
InterfaceError: (pyodbc.InterfaceError) ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
(Background on this error at: http://sqlalche.me/e/rvf5)
If you are going to use Windows authentication then you simply omit the username/password part of the connection URI. This works fine for me:
connection_uri = (
"mssql+pyodbc://#192.168.0.179:49242/mydb?driver=ODBC+Driver+17+for+SQL+Server"
)
engine = sa.create_engine(connection_uri)

Can't establish connection SQL Server using sqlalchemy

I'm trying to use Python to upload from a Pandas dataframe to a SQL Server table, but I can't successfully create a connection using sqlalchemy. I understand I first need to create an engine object using create_engine(), and create a connection object using engine.connect(), but no string I enter in create_engine() seems to work. I've tried the following:
engine = create_engine('mssql+pyodbc://myServer/myDB')
conn = engine.connect()
and:
engine = create_engine('mssql+pyodbc://Server=myServer;Database=myDB;')
conn = engine.connect()
and:
engine = create_engine('mssql+pyodbc://Driver={SQL Server};Server=myServer;Database=myDB;Trusted_Connection=yes;')
conn = engine.connect()
but all result in the following error:
InterfaceError: (pyodbc.InterfaceError) ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
I've also tried:
engine = create_engine('mssql+pyodbc://Driver={SQL Server Native Client 11.0};Server=myServer;Database=myDB;Trusted_Connection=yes;')
conn = engine.connect()
which results in the following error:
DBAPIError: (pyodbc.Error) ('IM010', '[IM010] [Microsoft][ODBC Driver
Manager] Data source name too long (0) (SQLDriverConnect)')
While I can successfully connect using pyodbc like this:
conn = pyodbc.connect('DRIVER={SQL Server};Server=myServer;Database=myDB;Trusted_Connection=yes;')
I can't seem to make this work for sqlalchemy.
Any help would be appreciated.
The solution:
engine = create_engine('mssql+pyodbc://ERRSTSDBP2/ActPri?driver=SQL+Server+Native+Client+11.0')
Thanks to norbeq for getting me most of the way there!
You can try connection like this:
engine = create_engine('mssql+pyodbc://user:password#host:port/myDB')
conn = engine.connect()

Python to SQL Connection. Trying to push pandas dataframe to SQL Server

Anyone know how to solve this error? Trying to connect to Azure SQL Server.
Thanks a ton!
InterfaceError: (pyodbc.InterfaceError) ('IM002', u'[IM002]
[Microsoft][ODBC Driver Manager] Data source name not found and no
default driver specified (0) (SQLDriverConnect)') (Background on this
error at: http://sqlalche.me/e/rvf5)
Without your code, but just from the error message, it seams that there is some issue with your connection string.
You can use the code below for test:
import pyodbc
from sqlalchemy import create_engine
import urllib
params = urllib.quote_plus \
(r'Driver={ODBC Driver 13 for SQL Server};Server=tcp:yourDBServerName.database.windows.net,1433;Database=dbname;Uid=username#dbserverName;Pwd=xxx;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;')
conn_str = 'mssql+pyodbc:///?odbc_connect={}'.format(params)
engine_azure = create_engine(conn_str,echo=True)
print('connection is ok')
Hope it helps. And please let me know if any further issue.

Why is the SQL server DB engine not connecting with SQLAlchemy engine?

I am trying to connect to the SQL server database on python platform using SqlAlchemy. I am using windows authentication to connect to my the SQL server. On connecting the server the SqlAlchemy engine is throwing an error:
Below is the code I have implemented:
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
import pyodbc
Driver Server Name Instance Database
DATABASE_URL='mssql+pyodbc://DESKTOP-N32LSOV\PRANAV/AdventureworksDW2016CTP3?trusted_connection=yes'
Engine = create_engine(DATABASE_URL)
cn = Engine.connect()
When the above code is run, this error is produced:
Error:sqlalchemy.exc.InterfaceError: (pyodbc.InterfaceError) ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') (Background on this error at: http://sqlalche.me/e/rvf5)
I tried using pymssql driver inplace of pyodbc driver but still the error persists. On contrary when i try to connect to the using the below syntax it connects. I guess i am missing some attribute in the mssql url.
pyodbc.connect(r'Driver={SQL Server};Server=DESKTOP-N32LSOV\PRANAV;Database=master;Trusted_Connection=yes;')
Any help will be appreciated.
You need to specify both that you want to use ODBC and what ODBC driver to use.
engine = sqlalchemy.create_engine('mssql+pyodbc://localhost/Sandbox?driver=SQL+Server+Native+Client+11.0')
If you add the driver= part to your database url, it should work.
If all else fails, I would try using the creator argument to create_engine (documentation):
def creator():
return pyodbc.connect(r'Driver={SQL Server};Server=DESKTOP-N32LSOV\PRANAV;Database=master;Trusted_Connection=yes;')
Engine = create_engine('mssql://', creator=creator)
Using creator= bypasses all connection parameters specified in the URL, so you should only pass information to specify the DB dialect in the URL.
Looking at the mssql+pyodbc dialect/driver documentation, there is also the ?odbc_connect option:
import urllib.parse
CONNECTION_STRING = r'Driver={SQL Server};Server=DESKTOP-N32LSOV\PRANAV;Database=master;Trusted_Connection=yes;'
Engine = create_engine('mssql+pyodbc:///?odbc_connect=' + urllib.parse.quote_plus(CONNECTION_STRING))

Categories

Resources