Cannot connect to Oracle using python 3.4 - python

I just started to learn python and try to connect to oracle 11g, but I always get following error
cx_Oracle.InternalError: No Oracle error?
Here is my simple script to connect to oracle
import cx_Oracle as oracle
con = oracle.connect('user/password#ip:port/service')
Already try to look for any reference in other sites including here but can't find the solution. I don't think I have connection issue to oracle, because I use the same PC to connect to oracle using PHP.
Any advise would be appreciated, thanks.

One thing to keep in mind anytime you work with Oracle is that they use a proprietary connection protocol TNS (Transparent Network Substrate).
Therefore, you might need to use the cx_Oracle.makedsn(ip, port, SID) method and then pass it to cx_Oracle.connect() method to create your connection. Thus the general format on how to set up Oracle connection is:
import cx_Oracle
ip = 'xxx.xxx.xx.xxx'
port = 'xxxx'
SID = 'SID'
username = 'username'
password = 'password'
dsn_tns = cx_Oracle.makedsn(ip, port, SID)
db = cx_Oracle.connect(username, password, dsn_tns)
This is assuming you have already gotten cx_Oracle to work and import properly, which can be finicky depending on your environment.

Related

How to connect to MongoDB with using python

I'm pretty new to mongodb and i'm tryin to figure out how can I connect to my database with python externally.
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
in this example, you connect to your mongodb using a localhost, but I cant figure out how to connect my DB by remote and not locally. (More like, how do I get even a URI to put in there, im digging in mongodb website but im lost)
Thanks in advance!
From the documentation:, connection string:
mongodb://[username:password#]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]
What you need at least:
User
Password
Host (you are using localhost, you will need an ip or address to connect to a remote database)
Dabase name

How do I connect my python code to a mysql database hosted on the internet?

I have made a free account on https://www.freemysqlhosting.net which provides a free mysql database hosting facilities. I have created a database there, but I don't know how to connect to it from my python code on VSCode.
As of now, I am using a database that is on my computer.
This is the code in a config.py file that establishes connection to the MySQL server.
import mysql.connector as mysql
mysqlobj = mysql.connect(host='localhost', user='root',password='Mypass', database='timetable')
cursorobj = mysqlobj.cursor()
cursorobj.execute('USE timetable')
So how do I connect to a remote database on the said website with a piece of code that can be executed, because that way the connection can be established from any computer if they have the code to do so, without installing extensions(unless it's necessary).
If you require more details, please do ask in the comment section.
You should use remote address of server on which MySQL server is hosted and provide the IP address or Domain name exposed as connection properties to you in host,
import mysql.connector
config = {
'user': 'test',
'password': 'password',
'host': 'Remote IP or Domain Name',
'database': 'employees',
'raise_on_warnings': True
}
cnx = mysql.connector.connect(**config)
cnx.close()
This looks like a dup of Connecting to remote database located on web (freemysqlhosting.net‏) via visual studio c#. I've never used that service(looks pretty sketchy). They should provide you a connection string or at least the connection parts which consists of:
IP
port
username
password
database
NOTE: it's generally a bad idea to have a mysql server bound to ports exposed to the public internet, even with a username password.
I think you should be using pyodbc instead of mysql connector. That's what I remember using.
To install pyodbc it is a simple pip install pyodbc command
You may find more useful information here
If you're unable to connect to your hostedDB, try to whitelist your local IP address in your hosting server.
This might work.

How do I configure PyMySQL connect for SSL?

I'm trying to connect my database using SSL with PyMySQL, but I can't find good documentation on what the syntax is.
These credentials work in Workbench and with the CLI, but I get this error when using PyMySQL.
Can't connect to MySQL server on 'server.domain.com' ([WinError 10061] No connection could be made because the target machine actively refused it)")
db_conn = pymysql.connect(
host=db_creds['host'],
user=db_creds['user'],
passwd=db_creds['passwd'],
db=db_creds['db'],
charset=db_creds['charset'],
ssl={'ssl':{'ca': 'C:/SSL_CERTS/ca-cert.pem',
'key' : 'C:/SSL_CERTS/client-key.pem',
'cert' : 'C:/SSL_CERTS/client-cert.pem'
}
}
)
If I shut SSL off and drop the SSL parameter, I can connect unsecured just fine. What am I doing wrong with the SSL parameter?
Edit: PyMySQL now wants ssl parameters listed like this instead of in a dict.
db_conn = pymysql.connect(
host=db_creds['host'],
user=db_creds['user'],
passwd=db_creds['passwd'],
db=db_creds['db'],
charset=db_creds['charset'],
ssl_ca='C:/SSL_CERTS/ca-cert.pem',
ssl_key='C:/SSL_CERTS/client-key.pem',
ssl_cert='C:/SSL_CERTS/client-cert.pem'
)
Thanks for the help everyone. The syntax listed in the question is right, but the server I was attempting a connection to was using a non-standard port. I needed to add
port = db_creds['port']
Thanks, MannyKary, for the clue.
I had the same problem connecting pyMysql using client-side cert and key for users that REQUIRE X509, the TiDB (mySQL 5.7 compatible) server complained that no cert was supplied!!!
[2021/05/18 16:31:23.881 +00:00] [INFO] [privileges.go:258] ["ssl check failure, require x509 but no verified cert"] [user=mindline_root] [host=%]
Looking through the sourcecode of PyMysql 1.0.2, it appears that the ssl parameter is now a boolean instead of a ssl_dict, so you should put all your ssl parameters into individual arguements, e.g.,
db_conn = pymysql.connect(
host=db_creds['host'],
user=db_creds['user'],
passwd=db_creds['passwd'],
db=db_creds['db'],
charset=db_creds['charset'],
ssl_ca='C:/SSL_CERTS/ca-cert.pem',
ssl_key='C:/SSL_CERTS/client-key.pem',
ssl_cert='C:/SSL_CERTS/client-cert.pem'
)

How to connect to MS SQL Server database remotely by IP in Python using mssql and pymssql

How can I connect to MS SQL Server database remotely by IP in Python using mssql and pymssql modules.
To connect locally I use link = mssql+pymssql://InstanceName/DataBaseName
I enabled TCP/IP Network Configurations.
But How can I get the connection link?
Thank you.
You need to create a Connection object
import pymssql
ip = '127.0.0.1'
database_connection = pymssql.connect(host=ip, port=1433, username='foo', password='bar')
If you're using SQLAlchemy, or another ORM that supports connection strings, you can also use the following format for the connection string.
'mssql+pymssql://{user}:{password}#{host}:{port}'

Error 28000: Login failed for user DOMAIN\\user with pyodbc

I am trying to use Python to connect to a SQL database by using Window authentication. I looked at some of the posts here (e.g., here), but the suggested methods didn't seem to work.
For example, I used the following code:
cnxn = pyodbc.connect(driver='{SQL Server Native Client 11.0}',
server='SERVERNAME',
database='DATABASENAME',
trusted_connection='yes')
But I got the following error:
Error: ('28000', "[28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]
Login failed for user 'DOMAIN\\username'. (18456) (SQLDriverConnect); [28000] [Microsoft]
[SQL Server Native Client 11.0][SQL Server]Login failed for user 'DOMAIN\\username'.
(18456)")
(Note that I replaced the actual domain name and user name with DOMAIN and username respectively, in the error message above.)
I also tried using my UID and PWD, which led to the same error.
Lastly, I tried to change the service account by following the suggestion from the link above, but on my computer, there was no Log On tab when I went to the Properties of services.msc.
I wonder what I did wrong and how I can fix the problem.
Connecting from a Windows machine:
With Microsoft's ODBC drivers for SQL Server, Trusted_connection=yes tells the driver to use "Windows Authentication" and your script will attempt to log in to the SQL Server using the Windows credentials of the user running the script. UID and PWD cannot be used to supply alternative Windows credentials in the connection string, so if you need to connect as some other Windows user you will need to use Windows' RUNAS command to run the Python script as that other user..
If you want to use "SQL Server Authentication" with a specific SQL Server login specified by UID and PWD then use Trusted_connection=no.
Connecting from a non-Windows machine:
If you need to connect from a non-Windows machine and the SQL Server is configured to only use "Windows authentication" then Microsoft's ODBC drivers for SQL Server will require you to use Kerberos. Alternatively, you can use FreeTDS ODBC, specifying UID, PWD, and DOMAIN in the connection string, provided that the SQL Server instance is configured to support the older NTLM authentication protocol.
I tried everything and this is what eventually worked for me:
import pyodbc
driver= '{SQL Server Native Client 11.0}'
cnxn = pyodbc.connect(
Trusted_Connection='Yes',
Driver='{ODBC Driver 11 for SQL Server}',
Server='MyServer,1433',
Database='MyDB'
)
Try this cxn string:
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;PORT=1433;DATABASE=testdb;UID=me;PWD=pass')
http://mkleehammer.github.io/pyodbc/
I had similar issue while connecting to the default database (MSSQLSERVER). If you are connecting to the default database, please remove the
database='DATABASENAME',
line from the connection parameters section and retry.
Cheers,
Deepak
The first option works if your credentials have been stored using the command prompt. The other option is giving the credentials (UId, Psw) in the connection.
The following worked for me:
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=yourServer;DATABASE=yourDatabase;UID=yourUsername;PWD=yourPassword')
import pyodbc #For python3 MSSQL
cnxn = pyodbc.connect("Driver={SQL Server};" #For Connection
"Server=192.168.0.***;"
"PORT=1433;"
"Database=***********;"
"UID=****;"
"PWD=********;")
cursor = cnxn.cursor() #Cursor Establishment
cursor.execute('select site_id from tableName') #Execute Query
rs = cursor.fetchall()
print(rs)
A slightly different use case than the OP, but for those interested it is possible to connect to a MS SQL Server database using Windows Authentication for a different user account than the one logged in.
This can be achieved using the python jaydebeapi module with the JDBC JTDS driver. See my answer here for details.
Note that you may need to change the authentication mechanism. For example, my database is using ADP. So my connection looks like this
pyodbc.connect(
Trusted_Connection='No',
Authentication='ActiveDirectoryPassword',
UID=username,
PWD=password,
Driver=driver,
Server=server,
Database=database)
Read more here
Trusted_connection=no did not helped me. When i removed entire line and added UID, PWD parameter it worked. My takeaway from this is remove

Categories