I tried to connect using pyodbc like this and it worked:
self.connection = pyodbc.connect('Driver={ODBC Driver 18 for SQL Server};Server=' + server_full_name + ';Database=' + database + ';ENCRYPT=yes;UID=' + full_user+';PWD=' + self.db_password)
While I am trying to do the same thing using SQL Alchemy:
connection_string = 'Driver={ODBC Driver 18 for SQL Server};Server=' + server_full_name + ';Database=' + database + ';ENCRYPT=yes;UID=' + full_user+';PWD=' + self.db_password
self.connection = create_engine(f'mssql+pyodbc:///?odbc_connect={connection_string}').connect()
This doesn't work and I am getting the following error
sqlalchemy.exc.OperationalError: (pyodbc.OperationalError) ('08001',
'[08001] [Microsoft][ODBC Driver 18 for SQL Server]Neither DSN nor
SERVER keyword supplied (0) (SQLDriverConnect)'
EDIT:
The problem was that I was using python 3.8. Installed 3.10 and it works fine. If you want to make it work without installing a new version of Python use urllib.
When using a pass-through ODBC connection string to create a SQLAlchemy Engine object, the recommended approach is to use SQLAlchemy's URL object:
from sqlalchemy import create_engine
from sqlalchemy.engine import URL
connection_string = "Driver=…"
connection_url = URL.create(
"mssql+pyodbc",
query={"odbc_connect": connection_string}
)
engine = create_engine(connection_url)
Related
I have pc with Windows 10. I installed Microsoft SQL Server 2019. Next action, on Windows 10 I installed WSL2 (Ubuntu 20.04). I try to connect from WSL2 (Ubuntu 20.04) to MS SQL on Windows 10.
I have tried everything I know and what I have found. Below are two articles on the subject that I have tried with no success.
I opened the 1433 port in Windows Firewall, and tried use him and not in all options with server and driver. I tried use five options with server and two options with driver, you can see this options in code bellow. I tried edit file /etc/hosts, where I add IP-address 172.29.176.1 (it action describe in second link)
Connect to SQL Server on Windows from WSL2 with pyodbc - Connection Timeout
Connect to SQL Server running on Windows host from a WSL 2/Ubuntu sqlcmd
If connect to the MS SQL from Windows everything works.
What could be the problem, what am I doing wrong, I will be grateful for the help?!
import pyodbc
import pandas as pd
import socket
#server1 = f'{socket.gethostname()}.local'
#server2 = 'DESKTOP-2TUPNJK.local'
#server3 = '172.29.176.1' # this is IP-address WSL2 and this IP-address specified in WSL2 (Ubuntu 20.04) -> /etc/resolv.conf
#server4 = '192.168.1.4' # this is IP-address my PC on Windows 10
server5 = '127.0.0.1' # this is IP-address from /etc/hosts -> localhost
#driver1 = '{ODBC Driver 17 for SQL Server}'
driver2 = '/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.9.so.1.1'
cnxn = pyodbc.connect('DRIVER=' + driver2 + ';SERVER='+server5+';PORT=1433;DATABASE=Test;UID=user;PWD=Password')
df = pd.read_sql_query('SELECT name FROM sys.Tables', cnxn)
print(df)
I get next error:
pyodbc.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')
I managed to solve this issue:
First -> the server name must be the IP address of your PC (ipconfig in Windows cmd)
Second -> next step follow this instruction (I didn't set up -> ApexSQL tools)
And this is my code:
import pyodbc
import pandas as pd
cnxn = pyodbc.connect('DRIVER=/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.9.so.1.1;SERVER=192.168.0.2,1433;DATABASE=Test;UID=sa;PWD=Test')
df = pd.read_sql_query('SELECT * FROM sys.Tables', cnxn)
print(df)
I've been using this guide for connecting to database through pyodbc: https://github.com/mkleehammer/pyodbc/wiki/Connecting-to-SQL-Server-from-Mac-OSX
My config files look like this, in parallel with the tutorial:
In freetds.conf:
[MYMSSQL]
host = localhost
port = 1433
tds version = 7.3
In odbc.ini:
[MYMSSQL]
Description = Testing SQLServer
Driver = FreeTDS
Servername = MYMSSQL
In odbcinst.ini:
[FreeTDS]
Description=FreeTDS Driver for Linux & MSSQL
Driver=/usr/local/lib/libtdsodbc.so
Setup=/usr/local/lib/libtdsodbc.so
UsageCount=1
When I test the connection with "tsql -S MYMSSQL -U myuser -P mypassword", I get the error:
Error 20002 (severity 9):
Adaptive Server connection failed
There was a problem connecting to the server
Likewise, "isql MYMSSQL myuser mypassword" returns an error as well:
[ISQL]ERROR: Could not SQLConnect
EDIT: In the query console:
"SELECT ##SERVERNAME" returns "4a70ffff1294"
"SELECT ##SERVICENAME" returns "MSSQLSERVER"
"SELECT ##VERSION" returns "Microsoft SQL Server 2019 (RTM-CU8) (KB4577194) - 15.0.4073.23 (X64)"
tsql -S MYMSSQL
returns
locale is "en_US.UTF-8"
locale charset is "UTF-8"
using default charset "UTF-8"
Error 20002 (severity 9):
Adaptive Server connection failed
There was a problem connecting to the server
The server is running in a docker image. I am able to connect to it via pycharm's database tool with the 1433 port and the relevant password. Sadly, I'm not very experienced with managing servers. All help is much appreciated.
If you want to continue down that path, we need some more info. What's in your freetds.conf? Can you connect to your SQL Server from the machine you're trying to install FreeTDS on with telnet mssql.myhost.com 1433?
However, I find it easier to avoid using freetds.conf and odbc.ini, and just keep everything in Python. As long as you have properly configured odbcinst.ini, you should be able to do something like this:
import pyodbc
con = pyodbc.connect(
"DRIVER={FreeTDS};"
"SERVER=mssql.yourserver.com;"
"PORT=1433;"
"DATABASE=your_db;"
"UID=your_user;"
"PWD=your_pass;"
"TDS_Version=7.3;"
)
cursor = conn.cursor()
cursor.execute("SELECT 1")
for row in cursor.fetchall():
print(row)
Good luck!
Using a Raspberry Pi with Raspbian 9, I'm trying to connect to an Azure SQL database using ODBC (pip installed it from the shell) with FreeTDS (version 108)
Up until now, I have tried the following:
In /etc/odbcinst.ini:
[FreeTDS]
Description=FreeTDS Driver
Driver=/usr/lib/odbc/libtdsodbc.so
Setup=/usr/lib/odbc/libtdsS.so
In my /etc/odbc.ini
[name]
Driver=FreeTDS
ServerName = {MyServerString from Azure MS-SQL}
Database = {My database name from Azure MSQ-SQL}
TDS_Version = auto
In the FreeTDS.config file:
Created this block:
[name]
host = {MyServerString from Azure MSQ SQL}
port = 1433
tds version = auto
When I run the following command:
tsql -S {name} -U {my_username} -P {my_password}
I get the result
No errors ( 1> )
So I believe I am connected to the database.
However, when I run my Python code. I get an error. My database connection block is below
#Database setup
conDEBUG = "DRIVER={FreeTDS};Database={MyDGName};SERVER=tcp:{MyDB}.database.windows.net;UID={myUID};PWD={myPWD}"
conDEBUG = urllib.parse.quote_plus(conDEBUG)
conDEBUG = "mssql+pyodbc:///?odbc_connect=%s" % conDEBUG
app.config['SQLALCHEMY_DATABASE_URI'] = conDEBUG
db = SQLAlchemy(app)
I also tried adding 'TDS_Version=auto' to the conDEBUG string, this didn't work either.
The specific error I am getting:
('08001', '[08001] [unixODBC][FreeTDS][SQL Server]Unable to connect to data source (0) (SQLDriverConnect)')
Here's the function I use for connecting via SQLAlchemy to SQL Server over pyodbc:
def mssql_connect(con_string):
""" Connects to the specified db via ODBC. """
def connect():
return pyodbc.connect(con_string, autocommit=True)
db = create_engine('mssql://', creator=connect, encoding='cp1252')
db.echo = False
return db
mssql_connect("DRIVER={FreeTDS};SERVER={MyDB}.database.windows.net;PORT=1433;DATABASE={dbname};UID={myUID};PWD={myPWD};TDS_Version=7.3;")
Depending on your version of FreeTDS, you may have to replace TDS_Version=7.3 with TDS_Version=7.2 or TDS_Version=7.1. Good luck!
I am trying to connect to my SQL Server Database using python with pyodbc on my Mac. The full error I get when I run is:
libc++abi.dylib: terminating with uncaught exception of type std::runtime_error: collate_byname::collate_byname failed to construct for C/en_CA.
The Python code to connect using the driver is:
import pyodbc
cnxn = pyodbc.connect("Driver={ODBC Driver 17 for SQL Server}"
"Server=simvo-dbs.database.windows.net,1433;"
"Database=degree-planner-db;"
"UID=simvo_admin#simvo-dbs;"
"PWD=McGill_514;"
"loginTimeout=30;")
Other Relevant Files:
odbcinst.ini:
[ODBC Driver 17 for SQL Server]
Description=Microsoft ODBC Driver 17 for SQL Server
Driver=/usr/local/lib/libmsodbcsql.17.dylib
UsageCount=1
odbc.ini:
[MSSQL]
TDS_Version = 7.3
Driver = ODBC Driver 17 for SQL Server
Server = simvo-dbs.database.windows.net
Port = 1433
Any idea on what the issue is will be greatly appreciated. I am using a MAC.
I have the same issue and there is no solution, as far as I can tell. But you can workaround it running the script like this:
env LANG=C python3 myscript.py
I hope it helps.
Configuring freetds.conf (mac: /usr/local/etc/freetds.conf) allows you to reference the DSN configuration in the connection string instead of passing in characters which cause errors.
If you add in the following to the bottom of the freetds.conf:
[mssql]
host = db-name.random-string.region.rds.amazonaws.com
port = 1433
tds version = 8.0
client charset = UTF-8
And then you can pass in the DSN value in your connection string, which shouldn't cause any errors:
con_str = f"DSN=mssql,UID=username,PWD=XXXXXX"
con = pyodbc.connect(con_str) # shouldn't throw any errors
This information was adapted from this post: https://github.com/lionheart/django-pyodbc/wiki/Mac-setup-to-connect-to-a-MS-SQL-Server
I was getting the same error. I changed the settings to use ODBC Driver 13 for SQL Server, the error has gone away.
I am trying to connect to SQL Server using pyodbc. I am facing the following
problem:
My username is: DESKTOP-B3DDLU2\maria
Login failed for user 'DESKTOP-B3DDLU2\\maria'
Any idea how to overcome the \\ instead of \ problem? I using the following code:
conn = pyodbc.connect(
r'DRIVER={SQL Server};'
r'SERVER=DESKTOP-B3DDLU2\SQLEXPRESS;'
r'DATABASE=[xxx];'
r'UID=DESKTOP-B3DDLU2'+('\\')+r'maria;'
r'PWD=xxxxx')
Don't use \\ in a raw string when you only want a single \. e.g.
conn = pyodbc.connect(
r'DRIVER={SQL Server};'
r'SERVER=DESKTOP-B3DDLU2\SQLEXPRESS;'
r'DATABASE=[xxx];'
r'UID=DESKTOP-B3DDLU2\maria;'
r'PWD=xxxxx')
This worked for me:
Trusted_Connection=yes
example:
import pyodbc
connection_string ='DRIVER={ODBC Driver 11 for SQL Server};Server=<server>;Database=<DB>;Uid=<UID>;Trusted_Connection=yes'
connection = pyodbc.connect(connection_string)