QSqlDatabase connection - python

I have a server with a MariaDB Database.
Then I have a python program who run in a client where I have this code:
def Connect():
# Credential reading from register
servHost = RegRead("servHost")
servPort = RegRead("servPort")
dbName = RegRead("dbName")
__dbUser = RegRead("dbUser")
__dbPass = RegRead("dbPass")
con = QSqlDatabase.addDatabase('QODBC3')
driver = "DRIVER={MariaDB ODBC 3.1 Driver};"
database = f"Database={dbName};"
databaseName = driver+database
con.setDatabaseName(databaseName)
con.setHostName(servHost)
con.setPort(servPort)
if con.open(__dbUser, __dbPass):
print("Connected")
return True
else:
return False
I have made my program in a pc where I had both parts, so the database was in localhost and my pc was working as server and client at same time, then I changed it to a defined host. In my pc worked everything, but now that I have separeted server and client, I have problem to connect the client. The method Connect() return False and I don't understand what I am missing. I also remember that I installed a lot of things to let this work in my pc, but it was a lot of time ago and I don't remember what I did.
In the client, I have installed MariaDB ODBC Connector, I have the Driver "MariaDB ODBC 3.1 Driver" and made an User DNS who correctly connect to the database, but does not when it run in my program.
It run in my pc, so my code should be right. I think I missed some installation, maybe about Driver or some package, but I don't know what. Server is working too because I can make an User DNS. I did NOT install MariaDB Server (and I would not if not necessary). I have not installed anything except ODBC Connector and I imported only QSqlDatabase package.

I solved it. The method setHostName and the method setPort seem not to work. I think that it's because it require a QString object as parameter. I solved it adding the Host Name and Port to driver in this way
def Connect():
# Credential reading from register
servHost = RegRead("servHost")
servPort = RegRead("servPort")
dbName = RegRead("dbName")
__dbUser = RegRead("dbUser")
__dbPass = RegRead("dbPass")
con = QSqlDatabase.addDatabase('QODBC3')
driver = "DRIVER={MariaDB ODBC 3.1 Driver};"+f"Server={servHost};Port={servPort};" # This is the edit
database = f"Database={dbName};"
databaseName = driver+database
con.setDatabaseName(databaseName)
if con.open(__dbUser, __dbPass):
print("Connected")
return True
else:
return False

Related

Connect with Oracle Database via LDAP Authentication

I am using python's pyodbc library to connect with the Oracle Database. The authentication to my non-prod servers were set-up as Basic Authentication so my connection string worked well.
It was tough to understand and set up the right drivers initially, But then did manage to get through. Here is what the code looks like for connection and worked well for my other servers.
import textwrap
import pyodbc
connection_string = textwrap.dedent('''Driver={driver};
DBQ={hostname}:{port}/{sid};
UID={username};
PWD={password};
Connection Timeout=30;
Trusted_Connection="yes"
'''.format(driver = 'Oracle in instantclient_11_2',
hostname = <hostname>,
port = <port>,
sid = <sid>,
username = <username>,
password = <passwd>
))
connection = pyodbc.connect(connection_string)
To my surprise PROD is authenticated via LDAP only. To which I have the LDAP Server, Context, and DB Service along with the credentials.
I tried creating my connection string as
connection_string = textwrap.dedent('''Driver={driver};
DBQ={hostname}:{port}/{sid};
UID={username};
PWD={password};
Connection Timeout=30;
Authentication=LDAP;
Trusted_Connection="yes"
'''.format(driver = 'Oracle in instantclient_11_2',
hostname = <ldap_server>,
port = 389,
sid = <db_service>,
username = <username>,
password = <passwd>
))
To which I was not surprised to know it wont work. Tried going through many links but could not get through. Has anyone tried this before or please let me know what I must be missing.
I could definitely connect in SQL Developer using the LDAP Authentication. And since TNS Listener is not configured on this server I cannot use Basic Authentication to connect.
And help would be welcome on this.
Setting up Oracle Drivers - (This is a pre-requisite if exist please ignore)
Download Oracle Instant Client for Microsoft Windows (x64) 64-bit. Alternatively download available for your 32 bit system.
Choose your version of Oracle Database. My version was 11.2.0.4.0
Download below files -
i. Instant Client Package - Basic
ii. Instant Client Package - ODBC
Unzip both the packages into the same directory such as C:\oracle\instantclient_19_3.
Execute odbc_install.exe from the Instant Client directory. If Instant Client is 11g or lower, start the command prompt with the Administrator privilege.
Create C:\oracle\instantclient_19_3\network\admin folder to place tnsnames.ora, sqlnet.ora.
Set Environment variable - TNS_ADMIN to above folder location.
Add C:\oracle\instantclient_19_3 to PATH Environment variable.
Add C:\oracle\instantclient_19_3 to ORACLE_HOME (optional, if connection doesn't work try this.)
LDAP Authentication
Create two files: sqlnet.ora and ldap.ora
ldap.ora
# Place this file in the network/admin subdirectory or your
# $ORACLE_HOME location.
# LDAP Server name should be added here. Rest all the values remains unchanged.
DIRECTORY_SERVERS = (your-server.your-organization:389:636)
DEFAULT_ADMIN_CONTEXT = "ldap-ou-designation"
DIRECTORY_SERVER_TYPE = OID
sqlnet.ora
# Place this file in the network/admin subdirectory or your
# $ORACLE_HOME location.
SQLNET.AUTHENTICATION_SERVICES=(NTS)
NAMES.DIRECTORY_PATH = (LDAP)
Verify C:\oracle\instantclient_19_3 is present in the Path else try updating the path in the Python Code as below
import os
lib_dir=r"C:\oracle\instantclient_19_3"
os.environ["PATH"] = lib_dir + ";" + os.environ["PATH"]
With all this set-up in place you should have
username, password and DB Service name lets call it as db_service here
with cx_Oracle
import cx_Oracle
con = cx_Oracle.connect('{0}/{1}#{2}'.format(user, password, db_service))
version_script = "SELECT * FROM v$version"
cursor = con.cursor()
cursor.execute(version_script)
version = cursor.fetchall()
print(version[0][0])
Ouput
-----
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
with pyodbc
import pyodbc
con = pyodbc.connect('Driver={0};DBQ={1};UID={2};PWD={3}'.format(driver, db_service, user, password))
version_script = "SELECT * FROM v$version"
cursor = con.cursor()
cursor.execute(version_script)
version = cursor.fetchall()
print(version[0][0])
Ouput
-----
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
#Drivers for pyodbc
pyodbc.drivers()
Output
------
['ODBC Driver 17 for SQL Server',
'Oracle in instantclient_11_2']
References :
https://www.oracle.com/database/technologies/instant-client/winx64-64-downloads.html
https://www.oracle.com/database/technologies/releasenote-odbc-ic.html
https://eikonomega.medium.com/connecting-to-oracle-database-with-cx-oracle-and-ldap-5da7925a305c

How to connect to a remote Windows machine to change mdb file using python?

I am new to Python and I am trying to make a script that connects to a remote windows machine and change mdb file there. I can’t figure out how to work with the WMI library.
When I need to change mdb file (Access database) on my machine, I just use pyodbc connect. For example like this:
connStr = pyodbc.connect(r'DRIVER={Microsoft Access Driver (*.mdb)};'
r'DBQ=C:\Komax\Data\Topwin\DatabaseServer.mdb;')
cursor = connStr.cursor()
But now I need to run code on my machine so that it modifies the file (mdb) on the other machine. It seems like I have to use this code below to connect to remote machine, but I don't know what to do next, how to use connection. Please, help me to solve the problem :)
ip = "192.168.18.74"
username = "admin"
password = "komax"
from socket import *
try:
print("Establishing connection to %s" % ip)
connection = wmi.WMI(ip, user=username, password=password)
print("Connection established")
except wmi.x_wmi:
print("Your Username and Password of "+getfqdn(ip)+" are wrong.")

Connect to db2 database with Python

I'm working on an app that needs to connect to an ibm db2 database. Using DBeaver I can successfully connect to the database (I provide him the db2cc.jar and db2cc4.jar files).
It looks to me as DBeaver is using my Window's credentials to login, because I didn't need to input any login or password to connect.
Now, I've been trying to connect to the same database using python 3.7 and pypi's latest version of the ibm_db package. I didn't install anything else.
import ibm_db
# ...
connection_string = "DATABASE=" + self.params['schema'] + ";" + \
"HOSTNAME=" + self.params['host'] + ";" + \
"PORT=" + self.params['port'] + ";" + \
"PROTOCOL=TCPIP;" + \
"SECURITYMECHANISM=4;" + \
"UID=" + self.params['user'] + ";" + \
"PWD=" + self.params['password'] + ";"
try:
self.connection = ibm_db.connect(connection_string, "", "")
# ...
Using my Windows credentials in the parameters, I get the following error message:
Connection error
Bad credentials
SQLCODE=-30082
08001
From what I've seen on stack overflow connecting to a db2 database is complicated...
Does someone know how to connect ? Using the windows credentials or otherwise...
Thanks !
Db2 works fine with Python.
You need to be aware of some basics before you start such as:
what operating-system runs the target Db2-database and
what kind of client is being used (java, odbc/cli, .net etc), and
what kind of authentication/encrpytion is in place for the database
(ssl, server based authentication/+/-/encryption etc.).
is the remote database rdbms Apache DERBY or Db2.
Find out these basics before you start. You have to speak with people who run the Db2-server.
Note: in your question you mention (SecurityMechanism=4) com.ibm.db2.jcc.DB2BaseDataSource.USER_ONLY_SECURITY - this is not relevant for non-JAVA clients, it is relevant is the database manager is DERBY .
For python, the ibm_db package is not a java application.
DBeaver is a java application (hence it uses db2jcc.jar or db2jcc4.jar and a licence-file to connect to the remote database).
You can only use your Windows credentials for connecting to a Db2-database when that Db2-database run on Microsoft-Windows, and the credentials work on the hostname running the Db2-server. For any other combinations, the administrator must issue you a userid/password that is relevant for the target hostname.
The ibm_db package needs a Db2-client to be installed. The Db2-client is a separate installable. There are different kinds of Db2-client depending both on which operating-system runs your Db2-server and how much functionality you need to have in your Db2-client. If your remote Db2-server runs on Linux, Unix, Windows or Z/OS then you can use the "IBM Data Server Runtime Client" which you can either download from IBM's passport advantage website, or get from your internal IT folks. If your Db2-server runs on i-Series (AS/400) you should get its drivers from your i-Series administrator. For either Z/OS or i-Series you will additionally need a license file (which costs money) and you should get that from your administrator, unless your company uses a gateway product called Db2-connect in which case you don't need a separate license file on your workstation.
Try the following connection string, If your db2 client and server are on the same host.
Change the 'mydb' and 'DB2' (db2 instance name, you can get it with db2ilist utility) constants according your case.
ibm_db.connect('DATABASE=mydb;Instance=DB2;PROTOCOL=IPC;', '', '')
add ibm_db library and import ibm_db on top in the .py file.
def get_db_connection():
"""
This will help to get db2 connection for query execution
:return: conn
"""
dsn_driver = "{IBM DB2 ODBC DRIVER}"
dsn_database = "BLUDB"
dsn_hostname = "your_hostname"
dsn_port = "50000"
dsn_protocol = "TCPIP"
dsn_uid = "your_userid"
dsn_pwd = "your_pwd"
dsn = (
"DRIVER={0};"
"DATABASE={1};"
"HOSTNAME={2};"
"PORT={3};"
"PROTOCOL={4};"
"UID={5};"
"PWD={6};").format(dsn_driver, dsn_database, dsn_hostname, dsn_port, dsn_protocol, dsn_uid, dsn_pwd)
try:
conn = ibm_db.connect(dsn, "", "")
print("Connected!")
return conn
except Exception:
print("\nERROR: Unable to connect to the \'" + dsn_database + "\' server.")
print("error: ", ibm_db.conn_errormsg())
exit(-1)
function get_db_connection() will return the connection object. On that connection object you can perform operation like:
conn = get_db_connection()
list_results = []
select_query = 'SELECT a.STATUS, a.ID FROM "TABLE_NAME" AS a'
print(select_query)
selectStmt = ibm_db.exec_immediate(conn, select_query)
while ibm_db.fetch_row(selectStmt) != False:
list_results.append(ibm_db.result(selectStmt, 'ID'))
ibm_db.close(conn)

Can you connect to a database on another pc?

I'm using MySQLdb for python, and I would like to connect to a database hosted on an other PC on the same network/LAN.
I tried the followings for host:
192.168.5.37
192.168.5.37:3306
http://192.168.5.37
http://192.168.5.37:3306
None of the above work, I always get the
2005, Unknown MySQL server host ... (0)
What might be the problem?
Code:
db = MySQLdb.connect(host="192.168.5.37", user = "root" passwd = "password", db = "test1")
You can use MySQL Connector/Python, a standardized database driver for Python.
You must provide username, password, host, database name.
import mysql.connector
conn = mysql.connector.connect(user=username, password=password,
host="192.168.5.37",
database=databaseName)
conn.close()
You can download it from: https://dev.mysql.com/downloads/connector/python/
The IP you posted are local IPs
Give it a try with your external IP (for example on this website)
https://www.whatismyip.com/
If it works with the external IP, then it's maybe a misconfiguration of your firewall.

SQLAlchemy PyODBC MS SQL Server DSN-less connection

Using python 2.7 and the MS odbc driver through pyodbc. My connection string looks like this:
mssql+pyodbc://myuser:mypass#serverip/instancename?driver=ODBC+Driver+11+for+SQL+Server
I am getting login failed. However if I use the same credentials and "serverip\instancename" in the microsoft sql server management studio, I can connect.
The thing that is driving me crazy is a couple of days ago, this same connection string worked for me but to a different sql server instance on the same machine.
So what I am trying to figure out is how to go about troubleshooting it.
Thanks for any pointers.
When learning sqlalchemy I had the same issue. This method worked for me:
import urllib
params = urllib.quote_plus("DRIVER={SQL Server Native Client 10.0};SERVER=dagger;DATABASE=test;UID=user;PWD=password")
engine = create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)
Which comes from the sqlalchemy documentation. It does not seem related to the login credentials, but the error message was the same for me and this worked.
ref http://docs.sqlalchemy.org/en/latest/dialects/mssql.html#pass-through-exact-pyodbc-string
I just went through this, the reason it fails is the port, each instance listens in a different port, so you need to point which port is for that instance.
my code is:
DBserver='host.abc.nt'
DBengine='devenv'
DBport='####'
DBname='mydb'
DBDriver='ODBC Driver 13 for SQL Server'
DBuser='user'
DBpwd='pass'
DBuserpass = DBuser if len(DBuser) > 0 else ''
DBuserpass = DBuserpass + ':' + DBpwd if len(DBuser) > 0 else ''
if len(DBengine) > 0:
DBserver = DBserver + '\\' + DBengine
engine = sa.create_engine(f'''mssql+pyodbc://{DBuserpass}#{DBserver}:{DBport}/{DBname}?driver={DBDriver}''')
query=engine.execute('SELECT DB_NAME(), ##SERVERNAME')
query.fetchall()
[('mydb', 'host\\devenv')]
With that you create the engine, there is no need for other libraries besides sqlalchemy
but if you want to know the port of the instance, you can use:
Github repository from gordthompson/sqlserverport
or in Windows you connect with SQL Studio (or anything else) do some selects the the DB and in the meanwhile in CMD run a netstat to get the port:
C:\Users\pla>netstat -qfa | findstr host
TCP 10.0.0.1:##87 host.abc.nt:4096 ESTABLISHED

Categories

Resources