Connect to SQL Server using pyodbc - sql-server

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)

Related

Creating a SQLAlchemy engine from a SQL Server ODBC connection string

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)

Error 20002 while trying to connect to a server through tsql (OS X)

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!

"Login timeout expired" error when accessing MS SQL db via sqlalchemy and pyodbc

So I have some trouble getting sqlalchemy and pyodbc working with a remote MS SQL Server. Local sqlcmd worked properly but not when I try to read the db via python code. Any help would be appreciated.
Environment:
Centos 7
SQLCmd version: Version 17.1.0000.1 Linux
MS SQL Server 6.01.7601.17514
Python 2.7
The following sqlcmd worked properly
sqlcmd -S {Host},{Port} -U {USER} -P {PWD} -Q "use {Database};"
Attempts to work with sqlalchemy or pyodbc directly didn't work. Error:
pyodbc.OperationalError: ('HYT00', u'[HYT00] [unixODBC][Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')
Code:
Attempt with pyodbc
conn = pyodbc.connect(
r'DRIVER={ODBC Driver 17 for SQL Server};'
r'SERVER=HOST,PORT;'
r'DATABASE=DATABASE;'
r'UID=UID;'
r'PWD=PWD'
)
Attempt with sqlalchemy:
create_engine('mssql+pyodbc://{user}:{password}#{host}:{port}/{database}?driver={driver}'.format(
user=user,
password=password,
host=host,
database=database,
port=port,
driver="ODBC+Driver+17+for+SQL+Server"
)).connect()
I can reproduce the error with sqlcmd if I remove the port from the command, so maybe the conn_string I am passing to pyodbc is not in the correct format?
The problem might be DNS related, as you can read here.
Try to use an IP address, instead of the hostname, in the connection string, or check your DNS configuration.
In my case, this happened when I didn't properly escape passwords that has special characters. This was my solution:
from urllib.parse import quote
...
passwd = 'p#ssw0rd!'
...
engine_string = f"mssql+pyodbc://{user}:{quote(passwd)}#{host}/{name}?driver=ODBC+Driver+17+for+SQL+Server"
What does your python code do? Problem might be multiple Connections calls. Dont open the connection in a loop. Or conn.close() at the wrong point.
Other problem could be a firewall rule issue, check it.
I use pymssql to acces to my sql server. Read the documentation and install pymssql and freetds-dev on your centos system. Maybe u need to edit freetds.conf and add the ip and port of your sql server.

SQL Server pyodbc Driver issue: libc++abi.dylib: terminating with uncaught exception of type std::runtime_error

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.

How can I connect to an SQL Server DB using jython and zxJDBC?

I'd like to connect to my SQL Server DB using zxJDBC, but I can't figure out which driver to use... My function looks like so:
def sqlServerConnect():
conn = 'jdbc:sqlserver://MYDB'
username = "username"
password = "password"
driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
try:
conn = zxJDBC.connect(jdbc_url, username, password, driver)
print "Connection successful"
except zxJDBC.DatabaseError, e:
print "Connection failed:", e
The error message reads as follows:
Connection failed: driver [com.microsoft.sqlserver.jdbc.SQLServerDriver] not found
I found a solution, which is to use Jython's -J switch to give the JVM (Java Virtual Machine) a -cp classpath argument with the location of the JDBC jar file, e.g.,
jython -J-cp sqljdbc4.jar myProgram.py

Resources