create oracle connection using function in python - python

I'm trying to create a function for oracle connection which will take the parameters as mentioned in below code, but seems some issue...
could anyone please help in understanding how it can be corrected and what i'm missing here?
import cx_Oracle
def sqlconnect(user,passwd,SID, query):
connStr = cx_Oracle.connect('user/passwd#SID')
cursor = connStr.cursor()
cursor.execute(query)
return cursor.fetchall()
if __name__ == '__main__':
sqlconnect('user','password','XEE','select * from dual')
Thanks in advance!

The string user/passwd#SID is not a valid connect string. Unless XEE is a tnsnames.ora entry you need to reference the host and service name in your connect string. You probably want something like this, instead:
def sqlconnect(user, passwd, dsn, query):
conn = cx_Oracle.connect(user=user, password=passwd, dsn=dsn)
cursor = conn.cursor()
cursor.execute(query)
return cursor.fetchall()
if __name__ == '__main__':
host = "my_host_name"
service_name = "XEE"
conn_string = f"{host}/{service_name}"
sqlconnect("user", "password", conn_string, "select * from dual")

You can refer below link which helps you to understand how Python connects to Oracle db and you are missing TNS entry or full service JDBC URL and below are some samples:
https://www.oracle.com/database/technologies/appdev/python/quickstartpythononprem.html
https://oracle.github.io/python-cx_Oracle/samples/tutorial/Python-and-Oracle-Database-Scripting-for-the-Future.html

I think there's also another way by using f-strings:
import cx_Oracle
def sqlconnect(user,passwd,dsn, query):
connStr = cx_Oracle.connect(f'{user}/{passwd}#{dsn}')
cursor = connStr.cursor()
cursor.execute(f'{query}')
return cursor.fetchall()
if __name__ == '__main__':
sqlconnect('user','password','localhost/SID','select * from dual')

Related

How to use a external variable into a SQL query's where condition?

I want to fetch data from PostgreSQL database through python script. In where condition I have to use a value from local variable called "lastrun" last run is nothing but I have stored the last time when the program gets executed in a file. After read that file I stored that value in a variable called "lastrun" and I wanna use it in the query.
lastrun="06/11/2020 08:20:50.949881"
def doQuery( conn ):
cur = conn.cursor()
cur.execute("SELECT accountno,req, type, site,ref FROM accounts WHERE created > lastrun")
records=cur.fetchall()
print("Using PyGreSQL…")
import pgdb
myConnection = pgdb.connect( host=hostname, user=username, password=password, database=database )
doQuery( myConnection )
myConnection.close()
I tried but nothing works for me. Please help me out.
Thanks in advance.
you can use python string formatting to achive this
lastrun="06/11/2020 08:20:50.949881"
def doQuery( conn ):
cur = conn.cursor()
cur.execute("SELECT accountno,req, type, site,ref FROM accounts WHERE created > '%s'"%lastrun)
records=cur.fetchall()
print("Using PyGreSQL…")
import pgdb
myConnection = pgdb.connect( host=hostname, user=username, password=password, database=database )
doQuery( myConnection )
myConnection.close()
for more info visit here.

Updating MySQL DB Using Python For Loop Does not Work

I am trying to update the data from 'Active' to 'Retired by loop through a list of devices from the specific text file.
Somehow, however, it does not filter the list of devices from the text file and update the corresponding data, making no changes to the database at all.
Could it have something to do with my for statement, or mysql statement that I came up with? Regardless of how many times I fix MYSQL, it still results the same.
What could be the problem?
Please take a look at the code below and see if there is any mistake I have made with regards to MYSQL-wise or Python-wise.
Thank you in advance for your great help. Much appreciated.
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=############;'
'Database=########;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('SELECT id, device_id, model_number, serial_number_1,\
status_1, user_name_1 FROM [Footprint].[fpscdb001_cmdb_004].[desktop]')
results = []
with open('H:\list.txt') as inputfile:
results = inputfile.read().splitlines()
SQL = """UPDATE [Footprint].[fpscdb001_cmdb_004].[desktop]
SET status_1 = "Retired"
WHERE device_id == %s"""
try:
for i in results:
cursor.execute(SQL, results[i])
cursor.commit()
# print(rowcount)
except:
conn.rollback()
finally:
conn.close()
It looks like the problem is both your SQL and your Python.
There is a problem with your SQL at this part: WHERE device_id == %s. In SQL, there is no ==. Instead, you use a single = to both set and check values. You should use WHERE device_id = ?.
In addition, you're using %s as a placeholder in your query. I'm not familiar with pyodbc, but a quick check of the docs looks like you should be using the ? as a placeholder.
So try this:
SQL = """UPDATE [Footprint].[fpscdb001_cmdb_004].[desktop]
SET status_1 = "Retired"
WHERE device_id = ?"""
Building on the answer that #RToyo wrote, you may be able to do this a little more quickly
we can build a list of "?" placeholders in the SQL, and then pass each item safely to the ODBC holder, using the * notation to explode the array of device id's into the ODBC execute() function. This allows you to both execute only one query, and do it securely, too
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=############;'
'Database=########;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('SELECT id, device_id, model_number, serial_number_1,\
status_1, user_name_1 FROM [Footprint].[fpscdb001_cmdb_004].[desktop]')
results = []
with open('H:\list.txt') as inputfile:
results = inputfile.read().splitlines()
SQL = """UPDATE [Footprint].[fpscdb001_cmdb_004].[desktop]
SET status_1 = "Retired"
WHERE device_id in ({})""".format(("?, " * len(results))[0:-2])
try:
if len(results) > 0:
cursor.execute(SQL, *results)
except:
conn.rollback()
finally:
conn.close()
Hope this helps someone.

odbc connection in python

i am writing this code but nothing is happening
import pyodbc
def main():
conn = pyodbc.connect("DRIVER={SQL Server}; server=DESKTOP;database=master;Trusted_Connection=yes;autocommit=TRUE")
cursor = conn.cursor()
query ="create table Python_
ticket(ID int IDENTITY (1,1),NAME text,GENDER text, Comment text)"
cursor = conn.execute(query)
if __name__ == "__main__": main()
Try adding a print(cursor) statement at the end of the main() function, and see what cursor is.

inserting into a database (mysql) via a python program [duplicate]

This question already has answers here:
How do I connect to a MySQL Database in Python?
(26 answers)
Closed 5 years ago.
i am familiar with python and also familiar with mysql and SQL. I am also clear on con, cur and commit, but my problem here is that im trying to make a small program in python (no need for a gui) to insert data into a mysql database, and bring it on my console or file. I'm confused where to start, i tried seeking google but i couldn't find any toturials about my issue, any help? a link or where to start. Also:
i know the python program can be written in an IDE or a text file, but how does it connect to mysql database? if im wrong please correct me.
SQLAlchemy is good: https://www.sqlalchemy.org/
Otherwise, using the conn/cur as you described is easy: https://www.tutorialspoint.com/python/python_database_access.htm
Go though the documentation to get yourself familiar with python, mysql and how to work with them together.
Although, the minimal code would look something like this :
import MySQLdb
query = "insert into DB_NAME values (1,2)"
try :
conn = MySQLdb.connect(host="",
user="",
passwd="",
db="")
cursor = conn.cursor()
cursor.execute(query)
conn.commit()
cursor.close()
conn.close()
except (MySQLdb.Error, Exception) as error :
print error
print "Insert data unsuccessful"
See the code below
import mysql.connector
from mysql.connector import MySQLConnection, Error
class SQL_Connect:
def __init__(self):
#-------------------------------------------------------
# Database Connection Param's
self.host_Address = 'Host Here'
self.database_Name = 'Database Name'
self.userName = 'User Name'
self.db_Password = 'Password'
#-------------------------------------------------------
def insert_IntoDB(self, Manufacturer, partNum, formFactor, socket, chipSet, memSlots, memType, maxMem, raidSup, onboardVid, crosFire_Sup, sli_Sup, sata6GBS, sataExpress, onboard_Ether):
test_Query = 'INSERT INTO motherboards (Manufacturer, modelNum, formFactor, socket, chipset, memSlots, memType, maxMem, raidSup, onboardVid, crosfireSup, sliSup, sata6GBS, sataExpress, onboardEther) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'
args = (Manufacturer, partNum, formFactor, socket, chipSet, memSlots, memType, maxMem, raidSup, onboardVid, crosFire_Sup, sli_Sup, sata6GBS, sataExpress, onboard_Ether)
try:
conn = mysql.connector.connect(host = self.host_Address, database = self.database_Name, user = self.userName, password = self.db_Password)
if conn.is_connected():
print 'MySQL Database Connection Established'
cursor = conn.cursor()
cursor.execute(test_Query, args)
conn.commit()
print 'Data Inserted!!!'
except Error as e:
print ('ERROR: ',e)
finally:
cursor.close()
conn.close()

Connect to SQL server from self made module

I currently have many scripts that connect to the same MSSQL database. I make the connection in each of the scripts, but for ease of use I want to put the connection in a module and call that module from my script. The code in my module connect_to_db.pyc looks like this:
import pyodbc
def sql_connect():
server="some_server.net"
port="1433"
user = "my_username#my_domain"
server="my_server"
database="my_database"
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=my_server,1433',
user=user,
password=password,
database=database)
c=conn.cursor()
Then, in my script I try to call this module and run a query:
from connect_to_db import sql_connect
sql_connect()
c.execute("SELECT * FROM table")
I get the error that the name c is not defined. I tried to define it as a global too, but it don't help. It must have something to do with my lack of understanding modules, but I can't figure out what.
You can return cursor in your sql_connect function
import pyodbc
def sql_connect():
server="some_server.net"
port="1433"
user = "my_username#my_domain"
server="my_server"
database="my_database"
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=my_server,1433',
user=user,
password=password,
database=database)
return conn.cursor()
And then you can use it as
from connect_to_db import sql_connect
c = sql_connect()
c.execute("SELECT * FROM table")
You are indeed missing a bit there:
in your function sql_connect, you assign to a local variable named c.
That variable is not existant outside your function.
If you want a connection variable to exist on module level, maybe try the following attempt:
In your "connect_to_db.py":
import pyodbc
def sql_connect():
server="some_server.net"
port="1433"
user = "my_username#my_domain"
server="my_server"
database="my_database"
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=my_server,1433',
user=user,
password=password,
database=database)
return conn.cursor()
cursor = sql_connect()
This creates a varibale "cursor" on the level of the module.
In another module, simply perform
from connect_to_db import cursor
to import the module's "cursor" member.
This should do the trick.
Hint: Please be advised that this approach may not be very elegant, in terms of software-engineering.
Edit:
Maybe, you may want to dive deeper into object-oriented programming?
class MSSQLConnector(object):
def __init__(self, server, port, database, user, password):
self.server = server
self.port = port
self.conn = pyodbc.connect('DRIVER={SQL Server};SERVER='{0},
{1}.format((self.server, self.port)), user, password, database)
def open_cursor(self):
return self.conn.cursor()
Which would be used in this fashion:
connector = MSSQLConnector("my_server", "1433", "my_database", "username", "secret-password")
cursor = connector.open_cursor()

Categories