Connecting to SQLServer 2005 with adodbapi - python

I'm very new to Python and I have Python 3.2 installed on a Win 7-32 workstation. Trying to connect to MSSQLServer 2005 Server using adodbapi-2.4.2.2, the latest update to that package.
The code/connection string looks like this:
conn = adodbapi.connect('Provider=SQLNCLI.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=XXX;Data Source=123.456.789');
From adodbapi I continually get the error (this is entire error message from Wing IDE shell):
Traceback (most recent call last):
File "D:\Program Files\Wing IDE 4.0\src\debug\tserver_sandbox.py", line 2, in
if name == 'main':
File "D:\Python32\Lib\site-packages\adodbapi\adodbapi.py", line 298, in connect
raise InterfaceError #Probably COM Error
adodbapi.adodbapi.InterfaceError:
I can trace through the code and see the exception as it happens.
I also tried using conn strings with OLEDB provider and integrated Windows security, with same results.
All of these connection strings work fine from a UDL file on my workstation, and from SSMS, but fail with the same error in adodbapi.
How do I fix this?

Try this connection string:
Initial Catalog=XXX; Data Source=<servername>\\<SQL Instance name>; Provider=SQLOLEDB.1; Integrated Security=SSPI
Update
Umm ok. Looking at the source for adodbapi I would have to say that you are suffering a COM error. (yeah I know the traceback says that). But specifically with initialising the relevant COM objects.
This means that your connection string has nothing to do with the traceback. I think a good place to start would be to make sure that your copy of pythoncom is up-to-date.
It could be that win32com/pythoncom does not support Python 3K (3.0 onwards) yet, but after a minute of googleing I have not found anything useful on that, I'll leave it to you.
This code should run successfully when you have fixed your problem (and should fail at the moment).
import win32com.client
import pythoncom
pythoncom.CoInitialize()
win32com.client.Dispatch('ADODB.Connection')
Also any exception that code throws would be useful to help debug your problem.

In case anyone else finds this thread looking for the resolution to a similar error that I saw with Python 2.7:
Traceback (most recent call last):
File "get_data.py", line 10, in <module>
connection = get_connection(r"XXX\YYY", "DB")
File "get_data.py", line 7, in get_connection
conn = adodbapi.connect(connstring)
File "C:\Python27\lib\site-packages\adodbapi\adodbapi.py", line 116, in connect
raise api.OperationalError(e, message)
adodbapi.apibase.OperationalError: (InterfaceError("Windows COM Error: Dispatch('ADODB.Connection') failed.",), 'Error opening connection to "Data Source=XXX\\YYY; Initial Catalog=DB; Provider=SQLOLEDB.1; Integrated Security=SSPI"')
In my case the simple solution was to install Python for Windows Extensions (pywin32) from here:
http://sourceforge.net/projects/pywin32/files/pywin32/Build%20219/

I had the same problem, and I tracked it down to a failure to load win32com.pyd, because of some system DLLs that was not in the "dll load path", such as msvcp100.dll
I solved the problem by copying a lot of these dll's (probably too many) into C:\WinPython-64bit-3.3.3.2\python-3.3.3.amd64\Lib\site-packages\win32

Related

"AttributeError: 'module' object has no attribute" - Can someone explain the meaning of this error message?

I'm trying to get the ODB library working. In the documentation at https://python-obd.readthedocs.io/en/latest/ it lists the following code:
import obd
connection = obd.OBD("/dev/ttyUSB0") # connects to USB or RF port
cmd = obd.commands.SPEED # select an OBD command (sensor)
response = connection.query(cmd) # send the command, and parse the response
print(response.value) # returns unit-bearing values thanks to Pint
print(response.value.to("mph")) # user-friendly unit conversions
When I put this in a file called test.py and I run it:
python2 test.py
I get the following error message:
Traceback (most recent call last):
File "test.py", line 1, in <module>
import obd
File "/home/ubuntu/obd.py", line 3, in <module>
AttributeError: 'module' object has no attribute 'OBD'
Stackoverflow comes up with several iterations of this error message, but none clearly explain the problem, only giving specific solutions to those libraries.
I guess it's obvious that I'm new to Python, and I'm having trouble interpreting this error message, even after several hours of writing several small Python programs. I am of course also interested in why the error message is so un-intuitive to a newcomer and where I can gain the common knowledge I might be missing, and I guess this is as good a case to discover that through as any.
So far I have figured out the following:
<module> refers to the name of my python script that I am trying to run.
The mistake I made at first, was to name my test.py file, initially obd.py. This conflicted with the import obd as it was trying to import the file itself - even after I deleted it! The reason was that when I tried to run it the first time, it created a file called obd.pyc - and even though obd.py was no longer there, import OBD found the initially created obd.pyc and tried to import that - which of course does not contain the OBD object from the library I was trying to use.
This is not the detailed answer I'm looking for, so please add a more detailed explanation - or a link to how Python compiling works, if you can.

Python Path.rglob failing on network error when encountering folder without permission

I am new to Python and have been using this site as a reference...thanks for everything, I have learned a ton. First question:
I am running a basic recursive file search with Path.rglob(). I am running into a error when it encounters a folder that it does not have permission to access. I am running Python 3.7 on Windows and connecting to a windows share on a network drive.
Here's my code:
scan_folder = pathlib.Path("//192.168.1.242/Media")
nfo_files = list(scan_folder.rglob("*.nfo"))
It works perfectly until I encounter a folder that I do not have permission to access, then it errors out with:
Traceback (most recent call last):
File "D:/Working/media_tools/media_tools/movies_nfo_cataloger.py", line 337, in <module>
nfo_files = list(scan_folder.rglob("*.nfo"))
File "C:\Users\ulrick65\Anaconda3\lib\pathlib.py", line 1094, in rglob
for p in selector.select_from(self):
File "C:\Users\ulrick65\Anaconda3\lib\pathlib.py", line 544, in _select_from
for p in successor_select(starting_point, is_dir, exists, scandir):
File "C:\Users\ulrick65\Anaconda3\lib\pathlib.py", line 507, in _select_from
entries = list(scandir(parent_path))
OSError: [WinError 59] An unexpected network error occurred: '\\\\192.168.1.242\\Media\\#recycle'
Process finished with exit code 1
I searched and found the following Issue for Pathlib that appears to have been fixed, however the error is different in my case as it points to "Unexpected network error" instead of permissions.
https://bugs.python.org/issue24120
I verified that this is indeed a permissions error, I do not have access to that Recycle folder as the user I am logged in as. I edited the permissions for that folder and gave myself access and the code runs fine after that.
I know I could use oswalk as it ignores these...but I figured given the bug fix I linked to above, so should path.glob however it doesn't. Also, using path.rglob() is pretty slick, one line of code and is fast (not that oswalk wouldn't be just as fast).
Any help is appreciated.

sqlanydb windows could not load dbcapi

I am trying to connect to a SQL Anywhere database via python. I have created the DSN and I can use command prompt to connect to the database using dbisql - c "DNS=myDSN". When I try to connect through python using con = sqlanydb.connect(DSN= "myDSN")
I get
`Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
con = sqlanydb.connect(DSN= "RPS Integration")
File "C:\Python27\lib\site-packages\sqlanydb.py", line 522, in connect
return Connection(args, kwargs)
File "C:\Python27\lib\site-packages\sqlanydb.py", line 538, in __init__
parent = Connection.cls_parent = Root("PYTHON")
File "C:\Python27\lib\site-packages\sqlanydb.py", line 464, in __init__
'libdbcapi_r.dylib')
File "C:\Python27\lib\site-packages\sqlanydb.py", line 456, in load_library
raise InterfaceError("Could not load dbcapi. Tried: " + ','.join(map(str, names)))
InterfaceError: (u'Could not load dbcapi. Tried: None,dbcapi.dll,libdbcapi_r.so,libdbcapi_r.dylib', 0)`
I was able to resolve the problem. I was never able to use the sqlanydb.connect. I ended up using pyodbc. So my final connection string was con = pydobc.connect(dsn="myDSN"). I think that sqlanydb is only fully functional with sqlanydb 17 and I was using a previous version.
Depending on how Sybase is locally installed, it could also be that the Python module really cannot find the (correct) library when looking up dbcapi.dll in your PATH. A quick fix for that is to create a new SQLANY_API_DLL environment variable (that's the initial None in the names the error message says it tried using; it takes priority over all the others) containing the correct path, usually something like %SQLANY16%\Bin64\dbcapi.dll depending on what version you have installed (Sybase usually creates an environment variable pointing to its installation folder on a per version basis).
One way to encounter the backtrace shown by the OP is running 64-bit Python interpreter, which is unable to load the 32-bit dbcapi.dll. Try launching with "py -X-32" to force a 32-bit engine, or reinstall using a 32-bit python engine.
Unfortunately sqlanydb's code that tries to be smart about finding dbcapi also ends up swallowing the exceptions thrown during loading. The sqlanydb author probably assumed that failure to load implies file not found, which isn't always the case.
I was stoked in this same problem, both windows system32 and 64.
I'm using Python 3.9 and I found that since Python 3.8 the cdll.LoadLibrary function does no longer search PATH to find library files.
To fix this, I created the enviroment variable SQLANY_API_DLL pointing to the route of sqlanywhere installation, in my case version 17, bin32 or bin64 depending on your system.

Pythons Console Module has made it impossible to type the tab key

I started using it on one of my programs a while back. Ever since, whenever I type the tab key on a console (cmd.exe instance) with python running, I get a readline internal error. Full traceback is as follows (note I haven't imported the cmd module in this context or even imported a script using it. I've simply started python, pressed tab and voila an exception):
<pre>
Traceback (most recent call last):
File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\lib\site-packages\pyreadline\console\console.py", line 768, in hook_wrapper_23
res = ensure_str(readline_hook(prompt))
File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\lib\site-packages\pyreadline\rlmain.py", line 571, in readline
self._readline_from_keyboard()
File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\lib\site-packages\pyreadline\rlmain.py", line 536, in _readline_from_keyboard
if self._readline_from_keyboard_poll():
File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\lib\site-packages\pyreadline\rlmain.py", line 556, in _readline_from_keyboard_poll
result = self.mode.process_keyevent(event.keyinfo)
File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\lib\site-packages\pyreadline\modes\emacs.py", line 243, in process_keyevent
r = self.process_keyevent_queue[-1](keyinfo)
File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\lib\site-packages\pyreadline\modes\emacs.py", line 286, in _process_keyevent
r = dispatch_func(keyinfo)
File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\lib\site-packages\pyreadline\modes\basemode.py", line 257, in complete
completions = self._get_completions()
File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\lib\site-packages\pyreadline\modes\basemode.py", line 200, in _get_completions
r = self.completer(ensure_unicode(text), i)
File "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\Lib\rlcompleter.py", line 80, in complete
readline.redisplay()
AttributeError: module 'readline' has no attribute 'redisplay'
</pre>
Before u ask, I installed python to the directory "C:\SP_CI_PROGRAMS\Languages\Python\3.6.1". It's accessible from the path variable. Also any scripts I design I place in a directory u can also access from the path variable (including one using the cmd module for python).
This may not seem like a pressing concern, especially seeing as I can just type 4 spaces instead, however using tabs is something I've become especially accustomed to and the second I type the tab key, anything I've written in a previous block is immediately lost as the traceback is printed. Please, can someone tell me how to fix this.
Edit: This is only within the python interpreter. Typing tab within a running program or something else doesn't pose any problems.
Tested solution for Windows 10 (17 January 2020)
Copy last traceback file path C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\Lib\rlcompleter.py
Open it with any text editor
If has VsCode use cmd and copy this
code C:\SP_CI_PROGRAMS\Languages\Python\3.6.1\Lib\rlcompleter.py
Look the line 80 which traceback tell us
Change these line (starts 79) like bellow and It will works
There will no error message and unnecessary tab more
...
if _readline_available: ## The old one is ##
if hasattr(readline, 'redisplay'): # if _readline_available:
readline.insert_text('\t') # readline.insert_text('\t')
readline.redisplay() # readline.redisplay()
return '' # return ''
...
Do not forget to relaunch your python terminal
Seems to be a continuing issue for Windows machines as seen on Github. A workaround seems to be uninstalling the pyreadline package.
Stop using pyreadline. It's been abandoned. What you're seeing is a known issue, but unless someone takes over pyreadline development, it's unlikely to ever be fixed.
pyreadline can be uninstalled by typing pip uninstall pyreadline in the command prompt. I was experiencing the same issue, but after uninstalling pyreadline, Tab key is working for me.
NOTE: To see the installed packages, type pip list in command prompt.
Well if you don't have permission on the machine. You won't be able to do those uninstall solutions.
So set the completer function. It will solve the problem and won't have weird behaviors. But the auto-completion won't work anymore. If you want it to work have a look at the documentation and implement it.
readline.set_completer(lambda t, s: [None][s])
What has worked for me (while the others did not for some unbeknownst reason) is the following:
In line 78:
if _readline_available:
if hasattr(readline, 'redisplay'):
readline.insert_text('\t')
readline.redisplay()
return ' ' * 4

Google Appengine and Python exceptions

In my Google Appengine application I have defined a custom exception InvalidUrlException(Exception) in the module 'gvu'. Somewhere in my code I do:
try:
results = gvu.article_parser.parse(source_url)
except gvu.InvalidUrlException as e:
self.redirect('/home?message='+str(e))
...
which works fine in the local GAE development server, but raises
<type 'exceptions.SyntaxError'>: invalid syntax (translator.py, line 18)
when I upload it. (line 18 is the line starting with 'except')
The problem seems to come from the 'as e' part: if I remove it I don't get this exception anymore. However I would like to be able to access the raised exception. Have you ever encountered this issue? Is there an alternative syntax?
You probably have an older Python version on your server. except ExceptionType as varname: is a newer syntax. Previously you needed to simply use a comma: except ExceptionType, varname:.
I was getting the same error because I was using the pydoc command instead of the pydoc3 command on a python3 file that was using python3 print statements (print statements with parenthesis).
Just FYI, another possible cause for this error - especially if the line referenced is early in the script (like line 2) is line ending differences between Unix and Windows.
I was running Python on Windows from a Cygwin shell and got this error, and was really puzzled. I had created the file with "touch" before editing it.
I renamed the file to a temp file name, and copied another file (which I had downloaded from a Unix server) onto the original file name, then restored the contents via the temp file, and problem solved. Same exact file contents (on the screen anyway), only difference was where the file had originally been created.
Just wanted to post this in case anyone else ran across this error and was similarly puzzled.

Categories

Resources