Connecting to Oracle Database Using Python - python

I am trying to connect to Oracle database using the following script;
import cx_Oracle
username = user
password = pwd
host = host
port = '1521'
service = service
dbconn = cx_Oracle.connect(username + '/' + password + '#'+ host + ':' + port + '/' + service)
But I got the following error;
TNS:Connect timeout occurred
Can anybody please suggest me what is going wrong here?

# importing module
import cx_Oracle
# Create a table in Oracle database
try:
con = cx_Oracle.connect('scott/tiger#localhost')
# Now execute the sqlquery
cursor = con.cursor()
# Creating a table srollno heading which is number
cursor.execute("create table student(srollno number, \
name varchar2(10), efees number(10, 2)")
print("Table Created successful")
except cx_Oracle.DatabaseError as e:
print("There is a problem with Oracle", e)
# by writing finally if any error occurs
# then also we can close the all database operation
finally:
if cursor:
cursor.close()
if con:
con.close()

Related

Timeout of pyodbc connection - recycle conn?

At the beginning of my process, I connect to a SQL Server database
conn = pyodbc.connect("DRIVER=" + driver + ";SERVER=" + server + ";PORT=" + port + ";DATABASE=" + dbn + ";UID=" + user +";PWD=" + pwd)
and then use that connection and execute queries with this code:
cur = conn.cursor()
try:
cur.execute(sql)
conn.commit()
if cur.description is not None:
data = pd.io.sql.read_sql_query(sql, conn)
return data
except Exception as err:
conn.rollback()
raise err
cur.close()
It works fine until the code does not execute a query for several hours, then I get the following error:
cur.execute(sql)
pyodbc.OperationalError: ('08S01', '[08S01] [FreeTDS][SQL Server]Write to the server failed (20006) (SQLExecDirectW)')
It seems that there is a timeout. Is there any way to recycle the existing connection (conn)?

Connect to MySQL on GCE using Google Colaboratory

I am trying to access MySQL on GCE VM instance through Google Colaboratory though, unfortunately, it does not work properly but does work in the local VSCode environment.
While executing TestExec.py, it shows SSH Connected so it seems that ssh connection is successfully done though, however, it seems to be stuck on MySQL connection.
Output on Google Colab:
Please help with the solutions/tips?
sqlList = []
sqlList.append("select * from table name;")
HOST = 'ComputeEngine PublicIP'
PORT = 22
USER = 'username'
DBUSER = 'username for db'
KEY_FILE = 'private key file path'
DBNAME = 'dbname'
DBPORT = 3306
SSH_BASTION_ADDRESS = HOST
SSH_PORT = PORT
SSH_USER = USER
SSH_PKEY_PATH = KEY_FILE
MYSQL_HOST = HOST
MYSQL_PORT = 3306
MYSQL_USER = DBUSER
MYSQL_PASS = 'MySQL Login PW'
MYSQL_DB = DBNAME
with SSHTunnelForwarder(
(SSH_BASTION_ADDRESS, SSH_PORT),
ssh_pkey=SSH_PKEY_PATH,
ssh_username=SSH_USER,
# ssh_password=PASSPHRASE,
remote_bind_address=('localhost', MYSQL_PORT),
local_bind_address=('localhost', MYSQL_PORT)
) as ssh:
print("SSH Connected")
print(ssh.local_bind_port)
try:
connection = mysql.connector.connect(
host='localhost',
port = ssh.local_bind_port,
user=MYSQL_USER,
passwd=MYSQL_PASS,
db=MYSQL_DB,
charset='utf8'
)
print(connection.is_connected())
print("DB Connected")
cur = connection.cursor()
sql = "use dbname"
cur.execute(sql)
# rows = cur.fetchall()
# for row in rows:
# print(row)
for i in range(len(sqlList)):
print(sqlList[i])
sql = str(sqlList[i])
# sql = 'create table test (id int, content varchar(32))'
cur.execute(sql)
rows = cur.fetchall()
for row in rows:
print(row)
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
connection.rollback()
raise err
finally:
cur.close()
connection.commit()
connection.close()
It seemed the error occurred because of the connection. I have changed the method of connection.
import pymysql.cursors
connection = pymysql.connect(
host='localhost',
user='user',
password='password!',
db='dbname',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)

MySQL remote query works, but remote insert fails via Python

I'm running Ubuntu 16.04 with MySQL. I've opened the MySQL server for remote connections, and my remote Python script can query my database, but all attempts to INSERT fail without any error log entry.
It also looks like my remote INSERTs are being seen, because my AUTO_INCREMENT ID increases without entries being made when I run the Python INSERT code.
Any insight is appreciated!
Simple table schema:
CREATE TABLE test (
ID int NOT NULL AUTO_INCREMENT,
x INT,
PRIMARY KEY (ID)
);
This works directly on the server:
INSERT INTO test (x) VALUES (10);
This is the Python query that's working:
try:
connection = db.Connection(host=HOST, port=PORT, user=USER, passwd=PASSWORD, db=DB)
cursor = connection.cursor()
print("Connected to Server")
cursor.execute("SELECT * FROM test")
result = cursor.fetchall()
for item in result:
print(item)
except Exception as e:
print('exception connecting to server db: ' + str(e))
finally:
print('closing connection...')
connection.close()
And the Python INSERT that's not working:
try:
connection = db.Connection(host=HOST, port=PORT, user=USER, passwd=PASSWORD, db=DB)
cursor = connection.cursor()
print("Connected to Server")
cursor.execute("INSERT INTO test (x) VALUES (10);")
except Exception as e:
print('exception connecting to server db: ' + str(e))
finally:
print('closing connection...')
connection.close()
Thanks
Add this line after the execute() call:
cursor.execute("INSERT INTO test (x) VALUES (10)")
connection.commit()
When making changes to the db, it is required that you commit your changes, no change(s) would take effect.

Connect to lan database using python

I have set up xampp to both of my PCs with success. When I try to connect to the localhost of PC 1 while I am on PC 1 through python, everything works fine.
But when I am trying to connect to PC 2 xampp sql I cant get a connection.
I have cofigured xampp to accept connections from other devices in the lan and I can access it perfectly through my web browser but not from my python programm.
This is my code:
def GetResults(self):
try:
cnx = mysql.connector.connect(user='test', password= '123456', host='paraliass-pc', port='3306', database='test')
cursor = cnx.cursor()
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your username or password")
self.statusBar().showMessage("Wrong Username or Password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
self.statusBar().showMessage("Database does not exist")
if cnx :
print("Connected")
self.statusBar().showMessage("Connected")
cursor = cnx.cursor()
cursor.execute("SELECT * FROM STAFF WHERE NAME LIKE '" + self.textEdit.text() + "%' OR SURNAME LIKE '" + self.textEdit.text() + "%'" + "OR RANK LIKE '" + self.textEdit.text() + "%'")
I am getting this error which does not appear when I am connecting to the same pc I am running the program on
UnboundLocalError: local variable 'cnx' referenced before assignment
By the way, if i change the username or password on the localhost to be wrong on purpose, I get the same error.
You should consider granting privileges to connect remotely to MySQL, and bind MySQL to use the IP address and port of your choosing. By default, MySQL will only listen for connections via localhost/socket.

Python - can't connect to database

I'm learning python , I'm trying to connect to database:
OS Ubuntu 13.04
I have running the apache and localhost
Im using eclipse pydev
I have installed the mysql connector downloaded from here:http://dev.mysql.com/downloads/connector/python/ (a .deb file)
I have installed the sudo apt-get install python-mysqldb
List item
This is my code (simple)(with proper indent):
#!/usr/bin/python
import MySQLdb
try:
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="root", # your password
db="Ayuda") # name of the data base
except Exception as a:
print a
cur = db.cursor()
cur.execute("SELECT * FROM YOUR_TABLE_NAME")
for row in cur.fetchall() :
print row[0]
So I get this error:
(2002, "Can't connect to local MySQL server through socket
'/var/run/mysqld/mysqld.sock' (2)")
How do I solve this?
I have resolved: I used another code taken from mysql example of use: http://dev.mysql.com/doc/connector-python/en/myconnpy_example_connecting.html
this is my code now:
import mysql.connector
from mysql.connector import errorcode
try:
cnx = mysql.connector.connect(host="localhost",
user="root",
passwd="root",
db="Ayuda")
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exists")
else:
print(err)
else:
cur = cnx.cursor()
cur.execute("SELECT * FROM mitabla")
for row in cur.fetchall() :
print row[1]
cnx.close()
I still don't know why I could'connect the other way.

Categories

Resources