Unable to connect to server with python and pymssql - python

I'm developing a script that it's supossed to read data from a Microsoft SQL database and display it in a nice format. Also, It's supossed to write into the database as well. The issue is that I'm not able to connect to the server.
I'm using this code:
import pymssql
server = "serverIpAddress"
user = "username"
password = "pass"
db = "databaseName"
port = 1433
db = pymssql.connect(server,user,password,port= port)
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print "Database version : %s " % data
# disconnect from server
db.close()
And I'm getting this traceback:
Traceback (most recent call last):
File ".\dbtest.py", line 9, in <module>
db = pymssql.connect(server,user,password,port= port)
File "pymssql.pyx", line 641, in pymssql.connect (pymssql.c:10824)
pymssql.OperationalError: (18452, 'Login failed. The login is from an untrusted domain and cannot be used with Windows authentication.DB-Lib error message 20018, severity 14:\nGeneral SQL Server e
rror: Check messages from the SQL Server\nDB-Lib error message 20002, severity 9:\nAdaptive Server connection failed (serverip:1433)\n')
I've changed some data to keep privacy.
This give me some clues about what it's going on:
The login is from an untrusted domain and cannot be used with Windows authentication
But I don't know how to fix it. I've seen that some people uses
integratedSecurity=true
But I don't know if there is something like this on pymssql or even if that it's a good idea.
Also, I don't need to use pymssql at all. If you know any other library that can perform what I need, I don't mind changing it.
Thanks and greetings.
--EDIT--
I've also tested this code:
import pyodbc
server = "serverIpAddress"
user = "username"
password = "pass"
db = "databaseName"
connectString = "Driver={SQL Server};server="+serverIP+";database="+db+";uid="+user+";pwd="+password
con = pyodbc.connect(connectString)
cur = con.cursor()
cur.close()
con.close()
and I'm getting this traceback:
Traceback (most recent call last):
  File ".\pyodbc_test.py", line 9, in <module>
    con = pyodbc.connect(connectString)
pyodbc.Error: ('28000', "[28000] [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user '.\\sa'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC SQL Server Driver][SQL Server]Lo
gin failed for user '.\\sa'. (18456)")

Related

Having an issue connecting to a SQL DB while using pyodbc. Error: SyntaxError: unexpected character after line continuation character

I'm trying to connect to a SQL Server DB from Python using pyodbc. I keep getting the error:
SyntaxError: unexpected character after line continuation character
I can't seem to figure out why. The DB is held on SQL Server 2012.
I'm new to Python, so if I'm making an egregiously silly error I apologize. So far, I've tried adding a ';' after the password and after the final parentheses. I've tried using {SQL Server} rather than {SQL Server Native Client 11.0}. I've changed Trusted Connection to yes as well. There is a username and password on the DB so I to use both.
import pyodbc
cnxn = pyodbc.connect(Driver = '{SQL Server Native Client 11.0}', Host = Name-DA\\SQLEXPRESS, database = TestDB, Trusted_Connection = tcon, username = user, password = pwd)
cursor = cnxn.cursor()
cursor.execute("select * from dbo.ProFormaData")
The error reads:
cnxn = pyodbc.connect(Driver = '{SQL Server Native Client 11.0}', Host
= Name-DA\SQLEXPRESS, database = DBName, Trusted_Connection = tcon, username = user, password = pwd)
^ SyntaxError: unexpected character after line continuation character
Process returned 1 (0x1) execution time : 0.075 s Press
any key to continue . . .
Hoping to just print out the data for now. This is a test for more data manipulation later.

Microsoft SQL Server Won't Connect Through Python

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="***")

Error when calling a procedure from pyodbc

This is my first question here. So, I am sorry if it is repeated or the formatting is off. I searched through other questions and the error is common but appears on multiple situations.
I have a very simple python code where I want to execute a procedure in MSSQL from pyodbc.
import pyodbc
conn = pyodbc.connect(r'DSN=myDSN')
cursor = conn.cursor()
query = r'{call myproc}'
cursor.execute(query)
I am using call instead of exec after reading that ODBC uses call for executing procedures in MSSQL.
The error I am getting is the following:
Traceback (most recent call last):
File "myscript.py", line 26, in <module>
cursor.execute(query)
pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]The current transaction has aborted, and any pending changes have been rolled back. Cause: A transaction in a rollback-only state was not explicitly rolled back before a DDL, DML or SELECT statement. (111233) (SQLExecDirectW)')
Thanks for the help
In case someone is having the same issue. I was able to find out what the problems was. When you open a connection with DSN, the autocommit is set to False. For some reason, this should be True for the code to work (this depends largely on what I was doing on MSSQL).
import pyodbc
conn = pyodbc.connect(r'DSN=myDSN', autocommit=True)
cursor = conn.cursor()
query = r'{call myproc}'
cursor.execute(query)
This runs well!
Here are two examples on how you can execute a stored proc in MS SQL Server through pyodbc:
Passing a NULL, and the VARCHAR 'tallen' as positional parameter variables:
cursor.execute('EXEC usp_get_user_data ?, ?', None, 'flipperpa')
Passing two VARCHAR values as named parameter variables:
cursor.execute('EXEC usp_get_user_data #user_full_name = ?, #user_username = ?', 'flip', 'flipperpa')
Then to loop through the returned data:
rows = cursor.fetchall()
for row in rows:
# Do stuff
print(row.user_id)
Good luck!
I had issue with executing the Stored procedure using the SQL server 2008. The first step I did is to go to control panel > Administrative tools > Data Sources (ODBC) > add the driver
The only change I made in my python code is use "{call procdev_2017}". I got an error when I tried using exec instead of call
import pyodbc
conn = pyodbc.connect(driver='{SQL Server Native Client 11.0}', server='XXXXXXX', database='XXX',
trusted_connection='yes', autocommit=True)
bepcur = conn.cursor()
ipcur.execute("{call procdev_2017}")

How to import sql via shell in Python?

I have case :
import pymysql
conn = pymysql.connect(host='127.0.0.1', unix_socket='/opt/lampp/var/mysql/mysql.sock', user='root', passwd=None, db='test')
cur = conn.cursor()
cur.execute("test < /mypath/test.sql")
cur.close()
conn.close()
I always get error :
1064 , "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'test < /mypath/test.sql' at line 1"
I tried to use source and it still failed. Did you know why?
Thank you.
Your error message says that the MySQL server can't understand
test < /mypath/test.sql' at line 1
If you're a long time *nix user, it seems intuitive that you should be able to use commands like this to pass various sorts of data streams to various programs. But that's not the way the Python sql API (or most language-specific) sql APIs works.
You need to pass a valid SQL query to the execute() method in the API, so the API can pass it to the database server. A vaild query will be something like INSERT or CREATE TABLE.
Look, the server might be on a different host machine, so telling the server to read from /mypath/test.sql is very likely a meaningless instruction to that server. Even if it did understand it, it might say File test.sql not found.
The mysql(1) command line client software package can read commands from files. Is that what you want?
>>> import MySQLdb
>>> db = MySQLdb.connect(host = 'demodb', user = 'root', passwd = 'root', db = 'mydb')
>>> cur = db.cursor()
>>> cur.execute('select * from mytable')
>>> rows = cur.fetchall()
Install MySQL-Python package to use MySQLdb.

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