Connecting to Microsoft SQL Server in Python - python

I'm currently running into the issue of being unable to connect to the a microsoft sql server database through python that I can connect to via Tableau. I'm attempting to track some historical data that we cannot keep within our database for future years. This uses windows authentication and I've confirmed it working from my local machine to the server in Tableau. However, I'm not sure what driver Tableau uses in order to make this connection. I have tried to connect via ODBC in Tableau and run into the same issue as I do in python.
import pyodbc
cnxn_write = pyodbc.connect(driver='{SQL Server}',
server='FQDN, Port Number\SQLEXPRESS',
database='DataAnalytics',
trusted_connection='yes'
)
Returns the following error code
---------------------------------------------------------------------------
OperationalError Traceback (most recent call last)
C:\Users\User\AppData\Local\Temp/ipykernel_6969/555555555.py in <module>
3 import pyodbc
4 import date
time
----> 5 cnxn_write = pyodbc.connect(driver='{SQL Server}',
6 server='server-name\SQLEXPRESS',
7 database='DataAnalytics',
OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC SQL Server Driver]Login timeout expired (0) (SQLDriverConnect)')
The following code returns the same error.,
import pyodbc
cnxn_write = pyodbc.connect(driver='{SQL Server}',
server='FQDN, Port Number',
database='DataAnalytics',
trusted_connection='yes'
)
Anyone have any thoughts on what driver I should be using to attempt to connect with this database? I've tried {SQL Server} and {ODBC Driver 17 for SQL Server}. Or is this more likely to be on the server side than on my end?
Thanks everyone!

So in case anyone else runs into this issue in the future. pyodbc was not properly connecting to the driver ODBC Driver 17 for SQL Server. My fix was creating a User DSN after running the Windows executable odbcad32.exe. That properly identified the server, credentials and mirror server for the database. I called this User DSN 'sqlexpress' and the following is my connect string now.
cnxn_write = pyodbc.connect(r'DSN=sqlexpress')
Sadly this feels more like a workaround than a solution, but it now properly connects to my database.

I had the same problem but this worked for me. I use mssql
import pymssql
conn = pymssql.connect(server='host:port', user='user', password='pass', database ='database')
#%%
cursor = conn.cursor()
cursor.execute('SELECT TOP 10 * from table;')
row = cursor.fetchone()
while row:
print(str(row[0]) + " " + str(row[1]) + " " + str(row[2]))
row = cursor.fetchone()

Related

Problem connecting to MySQL database using Python through ODBC

I'm having a problem establishing a connection to the MySQL database No matter what I try or change I seem to be getting the same error. I want to be able to use python to modify MySQL database using ODBC but being new to this I'm not sure how to go about it. This is the error message:
Traceback (most recent call last):
File "C:\Users\Lutho\PycharmProjects\pyODBC\main.py", line 17, in
conx = pyodbc.connect(f'''DRIVER={driver};
pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]Named Pipes Provider: Could not open a connection to SQL Server [53]. (53) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 17 for SQL Server]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (53)')
Code I used:
import pyodbc
# define the server and database name
driver = '{ODBC Driver 17 for SQL Server}'
server = 'Local instance MySQL80'
database = 'tarsdb'
username = 'root'
password = '1234'
# define connection string
conx = pyodbc.connect(f'''DRIVER={driver};
SERVER={server};
DATABASE={database};
Uid={username};
Pwd={password};''')
# create connection cursor
cursor = conx.cursor()
I also tried using Trusted_Connection=yes and moved my MySQL file into the same folder as my python file but nothing has worked. Is there something I'm missing that I don't know about? If you can solve my problem that would be much appreciated. (If the question looks messy, just know I had a problem formating it.)
The issue was trying to use the ODBC driver for Microsoft SQL Server when the target database was MySQL. ODBC drivers are not interchangeable between different database products.
Connecting to MySQL from Python is possible using pyodbc and "MySQL Connector/ODBC" but there are better alternatives, specifically mysqlclient or pymysql. Both are solid choices, although in many circumstances mysqlclient is significantly faster than pymysql.

pyodbc.OperationalError: ('HYT00', u'[HYT00] [unixODBC][Microsoft][ODBC Driver 13 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')

Using the SQL Server Management Studio (SSMS) Express, I can find the database and connect without problems.
But when I use pyodbc to connect to the same server using:
import pyodbc
Server = r"xxxER\xxxSQLSERV"
db = "xxxDB"
user = "xxx"
password = "xxxx"
conn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server + ';DATABASE=' + db +';UID=' + user + ';PWD=' + password)
By Using Pyhton in my local i am able to connect but when i am trying in linux server getting below error
pyodbc.OperationalError: ('HYT00', u'[HYT00] [unixODBC][Microsoft][ODBC Driver 13 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')
i tried with ODBC Driver 17 for SQL Server too but facing the same issue.Can any one please suggest me on this.
Microsoft's SQL Server ODBC drivers for Linux are unable to resolve instance names. You can use the free sqlserverport module to get the corresponding port number and use that to connect.
Try removing the instance from server and set it as
Server = "xxxER"
or if you have a port number append it as
Server = "xxxER,portNo"
I have this problem and solved my problem in here.
Just add version.
conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server + ';DATABASE=' + db +';UID=' + user + ';PWD=' + password)
If not work change version 17 to 13 if not to 11 .
List versions of ODBC.
Check your mssql network config, my problem was there.
Enable port 1433 for all IPs.
Now is working with IP and host name.
I am using SSH Tunnel with remote server port forward to localhost,1433. This pyodbc connection intermittently fails if using the approach:
cnxn = pyodbc.connect('driver={ODBC Driver 17 for SQL Server};Server=localhost, 1433;'...
Replacing localhost with 127.0.0.1 seems to be working all the time
cnxn = pyodbc.connect('driver={ODBC Driver 17 for SQL Server};Server=127.0.0.1, 1433;'
Incidentally also did same using Ruby and FreeTDS, and Localhost,1433 worked all the time.. Must be something inside the pyodbc package or their approach that sometimes drop some info to make the DBMS on server fail to respond/timeout
This worked for me:
mssql://DRIVER={ODBC Driver 17 for SQL Server};SERVER={server_address,PORT};DATABASE=<my_database>;UID=<my_username>;PWD=<my_password>

Need help connecting to SQL Server from Python Flask-Appbuilder

I'm new to Python + Flask + Flask Appbuilder but I am a professional Java developer. I've been working on a small app that I initially used SqlLite and now I want to move into SQL Server, which will be the production database.
I can't seem to get the connection right.
I have tried using a DSN but I get an error message indicating there is a mismatch between the driver and something else (Python?). The searches on this error seem to indicate the driver is 32 bit and Python is 64. Still I can't get that working so I thought I'd try to connect directly. I'd prefer not using a DSN anyway. I've searched the web and can't find an example that works for me.
I have imported pyodbc. This is the current way I'm trying to connect:
params = urllib.quote_plus("DRIVER={SQL Server};SERVER=devsql07:1433;DATABASE=DevOpsSnippets;UID=<user>;PWD=<password>")
SQLALCHEMY_DATABASE_URI = "mssql+pyodbc:///?odbc_connect=%s" % params
This produces the following error message:
2016-02-17 07:11:38,115:ERROR:flask_appbuilder.security.sqla.manager:DB Creation and initialization failed: (pyodbc.Error) ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]Invalid connection. (14) (SQLDriverConnect); [01000] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (ParseConnectParams()). (14)')
Can anyone help me get this connection correct?
I really appreciate any help.
if you are using pyodbc you should be able to connect this way
import pyodbc
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=yourServer;DATABASE=yourDatabase;UID=;PWD=')
#putting to use
SQL = "select Field1, Field2 from someTable"
cursor = cnxn.cursor()
cursor.execute(SQL)
row = cursor.fetchall()
for r in row:
print r[0] #field1
print r[1] #field2
The port should be specified through a comma. Specify the connection string as
DRIVER={SQL Server};SERVER=devsql07,1433;DATABASE.....

pyodbc connecting to SQL Server 2012 problems

Below is the traceback. I've read all the other SO threads, googled for over two hours, and cannot figure this out. Here is what I have tried:
Both SQL Authentication and Windows Authentication versions of the connection string.
Using the SQL Server name (text) and also the IP Address of the server
Including and Excluding port 1443 (the default tcp/ip port for the SQL server)
Creating new rules in Windows Firewall to allow both inbound/outbound TCP at port 1443
List item
Traceback (most recent call last):
File "pythonscript.py", line 75, in
conn = pyodbc.connect(driver='{SQL Server}', server='ipaddress,1443', database='master', uid='XYZ\login', pwd='password')
pyodbc.Error: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (17) (SQLDriverConnect); [01000] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (53)'
here are some examples of what I've tried for the connection string:
conn = pyodbc.connect('Trusted_Connection=yes', driver = '{SQL Server}',server = '1.1.1.1,1443', database = 'master')
then
conn = pyodbc.connect(driver='{SQL Server}', server='1.1.1.1,1443', database='master', uid='xyz\login', pwd='pwd'
then I also tried both of the above with the name of the server (text) rather than the IP address. I have no idea how to get this to work at this point.
Have you confirmed you have connectivity between the servers? Try telnet -
telnet serverName 1433
If that connects then you can focus on issues with Python or the connection string.
In your connection string change it to use the PORT parameter instead of the ,1433. Something like -
SERVER=1.1.1.1;PORT=1433;
I would also say you might be better off passing the whole string. Here is what I do on Linux using FreeTDS typically -
self.db_connection = pyodbc.connect("DRIVER=FreeTDS;SERVER=1.1.1.1;PORT=1433;DATABASE=myDB;UID=myUser;PWD=myPass;TDS_Version=8.0;")
CONNECTION FROM WINDOWS TO MS SQL SERVER DATABASE:
Here you have an example I use myself to connect to MS SQL database table with a Python script:
import pyodbc
server = 'ip_database_server'
database = 'database_name'
username = 'user_name'
password = 'user_password'
driver = '{SQL Server}' # Driver you need to connect to the database
port = '1433'
cnn = pyodbc.connect('DRIVER='+driver+';PORT=port;SERVER='+server+';PORT=1443;DATABASE='+database+';UID='+username+
';PWD='+password)
cursor = cnn.cursor()
If you are trying to connect from a Windows device to the DB, go to ODBC Data Source Administrator from Windows, and check if you have installed the driver:
Where is the ODBC data source administrator in a Windows machine.
The image is in spanish, but you only have to click on 'Drivers' tab, and check if the driver is there as in the image.
CONNECTION FROM LINUX/UNIX TO MS SQL SERVER DATABASE:
If you are working in Linux/Unix, then you shoud install a ODBC manager like 'FreeTDS' and 'unixODBC'. To configure them, you have some examples in the following links:
Example: Connecting to Microsoft SQL Server from Linux/Unix
Example: Installing and Configuring ODBC

Cannot establish connection to sql-server using pyodbc on Windows 7

I'm using ActivePython 2.7.2.5 on Windows 7.
While trying to connect to a sql-server database with the pyodbc module using the below code, I receive the subsequent Traceback. Any ideas on what I'm doing wrong?
CODE:
import pyodbc
driver = 'SQL Server'
server = '**server-name**'
db1 = 'CorpApps'
tcon = 'yes'
uname = 'jnichol3'
pword = '**my-password**'
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=server;DATABASE=db1;UID=uname;PWD=pword;Trusted_Connection=yes')
cursor = cnxn.cursor()
cursor.execute("select * from appaudit_q32013")
rows = cursor.fetchall()
for row in rows:
print row
TRACEBACK:
Traceback (most recent call last):
File "pyodbc_test.py", line 9, in <module>
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=server;DATABASE=db1;UID=uname;PWD=pword;Trusted_Connection=yes')
pyodbc.Error: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (17) (SQLDriverConnect); [01000] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (53)')
You're using a connection string of 'DRIVER={SQL Server};SERVER=server;DATABASE=db1;UID=uname;PWD=pword;Trusted_Connection=yes', you're trying to connect to a server called server, a database called db1, etc. It doesn't use the variables you set before, they're not used.
It's possible to pass the connection string parameters as keyword arguments to the connect function, so you could use:
cnxn = pyodbc.connect(driver='{SQL Server}', host=server, database=db1,
trusted_connection=tcon, user=uname, password=pword)
I had the same error message and in my case the issue was the [SQL Server] drivers required TLS 1.0 which is disabled on my server. Changing to the newer version of the SNAC, SQL Server Native Client 11.0 fixed the problem.
So my connection string looks like:
cnxn = pyodbc.connect(driver='{SQL Server Native Client 11.0}',
host=server, database=db1, trusted_connection=tcon,
user=uname, password=pword)
I had faced this error due to another reason.
It was because my server had a "port" apart from the address.
I could fix that by assigning the following value to "Server" parameter of the connection string.
"...;Server=<server_name>,<port#>;..."
Note that it is a 'comma' and not 'colon'/'period'
cnxn = pyodbc.connect(driver='{SQL Server}', host=server, database=db1,
user=uname, password=pword)
print(cnxn)
I removed "Trusted_Connection" part and it worked for me.
Different security risks exist with either method. If you use Sql Server authentication you expose your userid/password in the code. But at least you process with the same credentials. If you use Windows authentication you have to insure all the possible users are setup with the right permission in the Sql server. With Sql authentication you can setup just one user but multiple people can use that one Sql User permissions wise.
I had the same issue today. I was using localhost in the connectionstring. Got rid of the issue by replacing localhost woth 'server name',. My db and application are running in the same machine.
If you don't have server name
go to Sql server management studio and execute below query, which will give you the server name.
SELECT ##SERVERNAME
The connection string look as below
conn = pyodbc.connect('Driver={SQL Server};'
'Server=myServerName;'
'Database=mydb;'
'Trusted_Connection=yes;')

Categories

Resources