I've been connecting to a MSSQL SERVER 2008 database using Microsoft SQL Server Management Studio graphic interface, as depicted in this screenshot
I would like to connect to this database using a python script. I installed pymssql and I've failed to connect to the database. I tried the following command:
import _mssql
conn = _mssql.connect(server="POLIVEIRA-PC\\MSSQLSERVER2008", user="POliveira-PC\\POliveira", password="my_password", database="database_name")
with and without the user and password flags. I always end up with this error:
Traceback (most recent call last):
File "", line 1, in
File "_mssql.pyx", line 1887, in _mssql.connect (_mssql.c:20477)
File "_mssql.pyx", line 632, in _mssql.MSSQLConnection.init (_mssql.c:6169)
_mssql.MSSQLDriverException: Connection to the database failed for an unknown reason.
Can you help me connect to this database using Python (either using pymssql module or not). I'm not experienced with Python, nor do I with SQL, therefore I would like to do it in the simplest manner possible.
I'm running Windows 7 64 bit. Pyhton v2.7.9
I recommend you to use pyodbc, if you're using anaconda, use the 3.0.10 version of pyodbc, example:
import pyodbc
from urllib.parse import quote_plus
params = quote_plus("DRIVER={SQL Server};SERVER=POLIVEIRA-PC\\MSSQLSERVER2008;DATABASE=dbname;UID=userid;PWD=password")
try: cnxn = create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)
except Exception as e:
raise SystemExit('Error: Conexion Base de Datos SQL %s' % e)
And if the problem is a remote connection in this links they talk about it
https://blogs.msdn.microsoft.com/walzenbach/2010/04/14/how-to-enable-remote-connections-in-sql-server-2008/
http://akawn.com/blog/2012/01/configuring-sql-server-2008-r2-express-edition-for-remote-access/
Hope this works
You need to create a login with SQL Server authentication and then connect with this user:
(you'll need to connect this login to a user etc., but that's unrelated to logging in), then use
import pymssql
pymssql.connect(host=r"POLIVEIRA-PC\MSSQLSERVER2008", user='logintest', password='secret', database='database_name')
don't use the _mssql module directly.
Related
I am a complete noob when it comes to staging connections using python. How I understand it is, python already comes pre-packaged with sqlite3. I am using python 3.8.5.
Here is my attempt
connection = sqlite3.connect("\python\Lib\sqlite3")
It returns error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
sqlite3.OperationalError: unable to open database file
I got it now. So I just need to supply a filename where the database objects are stored.
I was incorrectly thinking that I would need to supply the folder location to the database.
connection = sqlite3.connect('test.db')
which stores the database objects in the test.db file within the python folder.
You don't connect to the package, you connect to a database file.
import sqlite3
con = sqlite3.connect('path/to/database.db')
Full info here.
We have an oracle database and i am trying to connect to oracle database using python in linux. We have installed "sqlalchemy" , "cx_Oracle" libraries.
When i try to execute the below python script, i am getting below error.
Error: sqlalchemy.exc.DatabaseError: (cx_Oracle.DatabaseError) DPI-1047:
Cannot locate a 64-bit Oracle Client library: "libclntsh.so: cannot open
shared object file: No such file or directory". See
https://oracle.github.io/odpi/doc/installation.html#linux for help
(Background on this error at: http://sqlalche.me/e/4xp6)
Is there any way without installing "Instant Client" , i can connect to oracle database and execute .... ?
Please help me with any suggestion
Below is the code.
import sqlalchemy
from sqlalchemy import types,create_engine
conn = create_engine('oracle://User:password#hostname:1521/?service_name=ABCD')
cur = conn
ABC = []
select = cur.execute("select EMPLOYEE_ID,EMPLOYEE_NAME from EMPLOYEE")
for line in select:
ABC.append(line)
print(ABC)
I am new to python and oracle, I have written the code for the connection to oracle database 11g but it gives an error:
import cx_Oracle
con=cx_Oracle.connect('sys/Satyam123#localhost/xe')
con.close(
)
It gives the following error in pycharm:
C:\Users\DELL\venv\module2\Scripts\python.exe
C:/Users/DELL/Desktop/PYTHON/module2/check.py Traceback (most recent
call last): File "C:/Users/DELL/Desktop/PYTHON/module2/check.py",
line 2, in
con=cx_Oracle.connect('sys/Satyam123#localhost/xe') cx_Oracle.DatabaseError: DPI-1047: 32-bit Oracle Client library cannot
be loaded: "The specified module could not be found". See
https://oracle.github.io/odpi/doc/installation.html#windows for help
Please download and install Oracle Client. (There are several editions of Oracle Client, but the instant one will do):
http://download.oracle.com/otn/nt/instantclient/122010/instantclient-basic-nt-12.2.0.1.0.zip
Once it is installed, the cx_Oracle python module will look for the Oracle libs (OCI) and load them.
I had the same issue. Please follow the link https://oracle.github.io/odpi/doc/installation.html and install Oracle Instant Client 64-bit or 32-bit as per your system version. Once this is installed python would automatically be able to find Oracle Client libraries and you can successfully connect to the database.
It seems like,there is issue related to PATH.You can try to install package with the IDE terminal.In your case just try to install a package with pycharm terminal.
After that try to execute below script:
import cx_Oracle
import db_config
user="test"
pw="test"
dsn="localhost:port/TEST" #here TEST is service id
con = cx_Oracle.connect(user, pw, dsn)
cur = con.cursor()
cur.execute("select * from test_table")
res = cur.fetchall()
for row in res:
print(row)
Still having an issue then you can refer :
[https://oracle.github.io/python-cx_Oracle/samples/tutorial/Python-and-Oracle-Database-Scripting-for-the-Future.html]
I need to connect to a test server and run a sql query using pyodbc. For that I first need to set ODBCINI environment variable. I tried including that in python code using subprocess.
import subprocess
import pyodbc
bashCommand = "export ODBCINI=~/odbc.ini"
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE, shell=True)
pyodbc.pooling = False
conn = pyodbc.connect(DSN='test',autocommit=True,ansi=True)
cur = conn.cursor()
Below is the error I get
Traceback (most recent call last):
File "my_si_web_impressions_bcookie_dealid.py", line 15, in <module>
conn = pyodbc.connect(DSN='tdwb',autocommit=True,ansi=True)
pyodbc.Error: ('IM002', '[IM002] [DataDirect][ODBC lib] System information file not found. Please check the ODBCINI environment variable. (0) (SQLDriverConnect)')
I guess it implies that it din't export the ODBCINI variable so it couldn't connect to server. Can anyone help?
This doesn't work as you intend because a subprocess that is spawned can only affect it's own environment, and thus the one of the processes it spawns (as they inherit it).
So your bash-command is essentially a NOP.
Instead, you need to manipulate your own environment, by using os.environ:
import os
os.environ["ODBCINI"]="~/odbc.ini"
Then your connect should work.
I tried using SQLobject from IMDbPY and Python said the driver didn't work- I'm running PostgreSQL 9.2.
C:\Users\dom\AppData\Roaming\Python\Scripts>python imdbpy2sql.py -d /imdb -u 'postgres://sid:asdf#host/imdb'
Traceback (most recent call last):
File "imdbpy2sql.py", line 501, in <module>
conn = setConnection(URI, DB_TABLES)
File "C:\Users\dom\AppData\Roaming\Python\Python27\site-packages\imdb\parser\sql\objectadapter.py", line 185, in setConnection
conn = connectionForURI(uri, **kw)
File "C:\Users\dom\AppData\Roaming\Python\Python27\site-packages\sqlobject\dbconnection.py", line 1004, in connectionForURI
connCls = self.dbConnectionForScheme(scheme)
File "C:\Users\dom\AppData\Roaming\Python\Python27\site-packages\sqlobject\dbconnection.py", line 1021, in dbConnectionForScheme
% (scheme, ', '.join(self.schemeBuilders.keys())))
AssertionError: No SQLObject driver exists for 'postgres (only sqlite, sapdb, postgresql, firebird, maxdb, rdbhost, sybase, interbase, psycopg, mysql, mssql, postgres)
I tried installing it again and activepython says it's already installed: –
C:\Users\dom\AppData\Roaming\Python\Scripts>pypm install sqlobject
skipping "sqlobject"; already installed at "%APPDATA%\Python" (2.7)
Any ideas on making imdbpy2sql.py/SQLobject work?
Use the DB URI without quotes (!).
Late, but from the imdb2py docs:
[OTHER REQUIRED MODULES]
Obviously SQLObject and SQLAlchemy can access databases only through other
specific modules/packages, that you need to have installed (e.g.:
'mysql-python' for MySQL, 'psycopg' for PostgreSQL, and so on).
Did you try installing those?