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.....
Related
I have an ongoing issue that I just can't solve. It concerns a Python script that loads data into a SQL server database.
import pyodbc
conn = pyodbc.connect(r'Driver={SQL Server};'
r'Server=tcp:MY-SRV-NAME\ABC,49133;'
r'Database=MyDatabase;'
r'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('SELECT coalesce(max(NextDate),?) FROM [dbo].[TableName]',b)
When I run it from my local machine it works fine, however when I run the same script from a server I get the following error:
conn = pyodbc.connect(r'Driver={SQL Server};'
pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]SSL Security error (18) (SQLDriverConnect); [08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (SECCreateCredentials()). (1)')
This is using the same user account both locally & on the server.
Can anyone help out?
Apologies if this appears like a duplicated issue, I've read through many similar sounding issues on StackOverFlow, but none of the solutions help. I know the code is fine as it runs ok locally, but I just can't get it running from the server.
Any advice would be very much appreciated.
Thanks
I too faced it some time back and did the following , please try and let me know:
Edit /etc/ssl/openssl.cnf
add or make the following change and let me know.
MinProtocol = TLSv1.0
CipherString = DEFAULT#SECLEVEL=1
or if its a window machine it could be a driver issue kindly change the driver to any one of the following and check
driver='{SQL Server Native Client 11.0}',
or driver={ODBC Driver 17 for SQL Server};
Also note you might need to download & install the windows odbc driver as given in the below link
https://learn.microsoft.com/en-us/sql/connect/odbc/windows/system-requirements-installation-and-driver-files?view=sql-server-ver15#installing-microsoft-odbc-driver-for-sql-server
thanks!
I've looked through some other things but haven't been able to find a working solution.
Here is my code:
conn = db.connect("Driver={SQL Server}; Server='Server';Database='Database_DW'; uid='uid'; pwd = 'pwd'")
I run this code and I get the following error:
DatabaseError: ('08001', '[08001] [Microsoft][ODBC SQL Server
Driver][DBNETLIB]SQL Server does not exist or access denied.')
I'm really at a loss here. I can log in fine through the SQL Server Client with the exact some credentials.
Consider adjusting connection strings as parameter values are not quoted. Right now, pypyodbc is attempted to find the 'Server' (quotes included) server.
conn = pypyodbc.connect("DRIVER={SQL Server};server=servername;database=databasename;" + \
"UID=username;PWD=***")
Alternatively, use keyword arguments:
conn = pypyodbc.connect(driver="{SQL Server}", host="servername", database="database",
uid="username", pwd="***")
I would like to connect to an Oracle database with python through pyodbc. I have installed oracle driver and I tried the following script:
import pyodbc
connectString = """
DRIVER={Oracle in OraClient12Home1};
SERVER=some_oracle_db.com:1521;
SID=oracle_test;
UID=user_name;
PWD=user_pass
"""
cnxn = pyodbc.connect(connectString)
I got the following error message:
cnxn = pyodbc.connect(connectString)
Error: ('HY000', '[HY000] [Oracle][ODBC][Ora]ORA-12560: TNS:protocol adapter error\n (12560) (SQLDriverConnect)')
What's wrong here?
Why keyword DBQ works and SID/Service Name does not, see the section 21.4.1 Format of the Connection String in Oracle 12c documentation.
https://docs.oracle.com/database/121/ADFNS/adfns_odbc.htm#ADFNS1183/
or google keywords for odbc oracle 12c
Looks Like your missing a PORT
Try this way
NOTE:
Depending on your Server the syntax can be different this will work for Windows without DSN using an SQL Server Driver.
connectString = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;PORT=1433;DATABASE=testdb;UID=me;PWD=pass')
This is the connection, you still need a cursor and to use execute along with an SQL Statement..
You have to specify server or hostname (or IP address in connection string for your database server is running.
So close...
connectString = """
DRIVER={Oracle in OraClient12Home1};
SERVER=some_oracle_db.com:1521;
DBQ=oracle_test;
Uid=user_name;
Pwd=user_name
"""
I replaced SID with DBQ
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;')
I have a local DB on my machine called 'Test' which contains a table called 'Tags'. I am able to access this DB and query from this table through SQL Server management studio 2008.
However, when using pyodbc I keep running into problems.
Using this:
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost:1433;DATABASE=Test')
yields the error:
pyodbc.Error: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]Invalid connection. (14) (SQLDriverConnectW); [01000] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Invalid Instance()). (14)')
(with or without specifying the port)
Trying an alternative connection string:
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost\Test,1433')
yields no error, but then:
cur = conn.cursor()
cur.execute("SELECT * FROM Tags")
yields the error:
pyodbc.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'Tags'. (208) (SQLExecDirectW)")
Why could this be?
I tried changing your query to
SELECT * FROM Test.dbo.Tags
and it worked.
I don't see any authentication attributes in your connection strings. Try this (I'm using Windows authentication):
conn = pyodbc.connect('Trusted_Connection=yes', driver = '{SQL Server}',
server = 'localhost', database = 'Test')
cursor = conn.cursor()
# assuming that Tags table is in dbo schema
cursor.execute("SELECT * FROM dbo.Tags")
For me, apart from maintaining the connection details (user, server, driver, correct table name etc.),
I took these steps:
Checked the ODBC version here (Windows 10) ->
(search for) ODBC ->
Select 32/64 bit version ->
Drivers ->
Verify that the ODBC driver version is present there. If it is not, use this link to download the relevant driver: here
Reference Link: here
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost:1433;DATABASE=Test')
This connection lack of instance name and the port shouldn't be writen like this.
my connection is this:
cn=pyodbc.connect('DRIVER={SQL Server};SERVER=localhost\SQLEXPRESS;PORT=1433;DATABASE=ybdb;UID=sa;PWD=*****')
enter image description here
Try replacing 'localhost' with either '(local)' or '.'. This solution fixed the problem for me.