How to Update oracle table using Python passing arguments - python-3.x

I need to pass 2 arguments to my update statement.
I first get the distinct ID's from TBL1 into a List as below. This works fine
unit_no=[]
sql = """SELECT DISTINCT(ID) FROM TBL1"""
tmp_cursor=self.DB_conn.cursor()
for rec in tmp_cursor.execute(self.orcl_query1)
unit_no.append(rec)
Then, I get a values from another table using the above result. This also is working fine.
while i < len(unit_no):
sql = 'SELECT COL1 FROM TBL2 WHERE ID = :1)
tmp_cursor1=self.DB_conn.cursor()
tmp_cursor1.execute(sql,unit_no[i])
for result in tmp_cursor1
input1=result
sql = """update tbl1 set col1 = :1 where id = :2"""
tmp_cursor2=self.DB_conn.cursor()
tmp_cursor2.execute(sQL,col1, unit_no[i])
I am getting error - function takes at most 2 arguments (3 given), for the above line.
How do I pass 2 values as input to the update statement

Related

SQL Server : MERGE statement, compare with select data instead of table data

merge into item_set TARGET
using (select '545934' as product_id_01, 4 as set_sort_no, 15 as article_id,
'Note for this item set' as note, 0 as is_deleted) as SOURCE
on TARGET.set_sort_no = SOURCE.set_sort_no and TARGET.product_id_01 = SOURCE.product_id_01
WHEN MATCHED THEN
UPDATE
SET TARGET.article_id = SOURCE.article_id,
TARGET.note = SOURCE.note,
TARGET.is_deleted = SOURCE.is_deleted,
TARGET.version = TARGET.version
WHEN NOT MATCHED THEN
INSERT (product_id_01, set_sort_no, article_id, note, is_deleted, version)
VALUES (SOURCE.product_id_01, SOURCE.set_sort_no, SOURCE.article_id, SOURCE.note, SOURCE.is_deleted, 3);
I have a query as shown above, I would like to know if it is possible to use multiple values(array of values) instead of the below statement from the query without using a table
(select
'545934' as product_id_01,
4 as set_sort_no, 15 as article_id,
'Note for this item set' as note, 0 as is_deleted) as SOURCE
Thanks in advance.
No.MS SQL Server was not designed to support arrays

How to execute multiple DML statements in a variable sequentially using cx_Oracle

I have a variable SCRIPT which has two to three DML statements. I want to run them sequentially after connecting to my Oracle DB. I have tried the below but it is failing with below error
c.execute(SCRIPT)
cx_Oracle.DatabaseError: ORA-00933: SQL command not properly ended
Below is the piece of code tried.
SCRIPT="""UPDATE IND_AFRO.DRIVER
SET Emp_Id = 1000, update_user_id = 'RIBST-4059'
WHERE Emp_Id IN (SELECT Emp_Id
FROM IND_AFRO.DRIVER Ddq
WHERE NOT EXISTS
(SELECT 1
FROM IND_AFRO_AF.EMPLOYEE
WHERE Emp_Id = Ddq.Emp_Id)
AND Functional_Area_Cd = 'DC');
UPDATE IND_AFRO.APPOINTMENTS
SET Emp_Id = 1000, update_user_id = 'RIBST-4059'
WHERE Emp_Id IN (SELECT Emp_Id
FROM IND_AFRO.APPOINTMENTS Ddq
WHERE NOT EXISTS
(SELECT 1
FROM IND_AFRO_AF.EMP
WHERE Emp_Id = Ddq.Emp_Id));
UPDATE IND_AFRO.ar_application_for_aid a
SET a.EMP_ID = 1000
WHERE NOT EXISTS
(SELECT 1
FROM IND_AFRO_AF.EMP
WHERE emp_id = a.emp_id);"""
conn = cx_Oracle.connect(user=r'SYSTEM', password='ssadmin', dsn=CONNECTION)
c = conn.cursor()
c.execute(SCRIPT)
c.close()
The execute() and executemany() functions only work on one SQL or PL/SQL statement.
You can wrap the three statements in a PL/SQL BEGIN/END block like:
SQL> begin
2 insert into test values(1);
3 update test set a = 2;
4 end;
5 /
PL/SQL procedure successfully completed.
Alternatively you can split up your string into individual statements. If the statements originate from a file, you can write a wrapper to read file and execute each statement. This is a lot easier if you restrict the SQL syntax (particularly regarding line terminators). For an example, see https://github.com/oracle/python-cx_Oracle/blob/master/samples/SampleEnv.py#L116
However this means calling execute() more times, which isn't as efficient as the first solution.

Error while getting user input and using Pandas DataFrame to extract data from LEFT JOIN

I am trying to create Sqlite3 statement in Python 3 to collect data from two tables called FreightCargo & Train where a train ID is the input value. I want to use Pandas since its easy to read the tables.
I have created the code below which is working perfectly fine, but its static and looks for only one given line in the statement.
import pandas as pd
SQL = '''SELECT F.Cargo_ID, F.Name, F.Weight, T.Train_ID, T.Assembly_date
FROM FreightCargo F LEFT JOIN [Train] T
ON F.Cargo_ID = T.Cargo_ID
WHERE Train_ID = 2;'''
cursor = conn.cursor()
cursor.execute( SQL )
names = [x[0] for x in cursor.description]
rows = cursor.fetchall()
Temp = pd.DataFrame( rows, columns=names)
Temp'''
I want to be able to create a variable with an input. The outcome of this action will then be determined with what has been given from the user. For example the user is asked for a train_id which is a primary key in a table and the relations with the train will be listed.
I expanded the code, but I am getting an error: ValueError: operation parameter must be str
Train_ID = input('Train ID')
SQL = '''SELECT F.Cargo_ID, F.Name, F.Weight, T.Train_ID, T.Assembly_date
FROM FreightCargo F LEFT JOIN [Train] T
ON F.Cargo_ID = T.Cargo_ID
WHERE Train_ID = ?;''', (Train_ID)
cursor = conn.cursor()
cursor.execute( SQL )
names = [x[0] for x in cursor.description]
rows = cursor.fetchall()
Temp = pd.DataFrame( rows, columns=names)
Temp
The problem lays in your definition of the SQL variable.
You are creating a tuple/collection of two elements. If you print type(SQL) you will see something like this: ('''SELECT...?;''', ('your_user's_input')).
When you pass this to cursor.execute(sql[, parameters]), it is expecting a string as the first argument, with the "optional" parameters. Your parameters are not really optional, since they are defined by your SQL-query's [Train]. Parameters must be a collection, for example a tuple.
You can unwrap your SQL statement with cursor.execute(*SQL), which will pass each element of your SQL list as a different argument, or you can move the parameters to the execute function.
Train_ID = input('Train ID')
SQL = '''SELECT F.Cargo_ID, F.Name, F.Weight, T.Train_ID, T.Assembly_date
FROM FreightCargo F LEFT JOIN [Train] T
ON F.Cargo_ID = T.Cargo_ID
WHERE Train_ID = ?;'''
cursor = conn.cursor()
cursor.execute( SQL, (Train_ID,) )
names = [x[0] for x in cursor.description]
rows = cursor.fetchall()
Temp = pd.DataFrame( rows, columns=names)
Temp

How to query/scan a table in DynamoDB using AND and OR in the same statement using python?

I want to query a table on DynamoDB and using python. The thing with this query is that I want to use an AND and OR condition in the same query. I want the query to retrieve values from one column when the value is B or C.
I have the following table:
domain validation_A validation_B validation_C
--------- ----------------- --------------- ---------------
drene.com pass pass pass
drene.com pass true pass
drene.com fail pass pass
In regular SQL expression I will use:
Select *
from
ValidationTable
where
domain = 'drene.com' and
validation_A = 'pass' and
(validation_B = 'pass' or validation_B = 'true')
I do not know how to do this in DynamoDB / Pythom
I tried the following:
response = table.scan(
IndexName="Date-index",
FilterExpression=Key('domain').eq('drene.com') & Attr('validation_A').eq('pass') & (Attr('validation_B').eq('pass') || Attr('validation_B').eq('true'))
)
But it is not working
I need the query bring me the first 2 rows.
Use | instead of ||
response = table.scan(
IndexName="Date-index",
FilterExpression=Key('domain').eq('drene.com') & Attr('validation_A').eq('pass') & (Attr('validation_B').eq('pass') | Attr('validation_B').eq('true'))

python oracle where clause containing date greater than comparison

I am trying to use cx_Oracle to query a table in oracle DB (version 11.2) and get rows with values in a column between a datetime range.
I have tried the following approaches:
Tried between clause as described here, but cursor gets 0 rows
parameters = (startDateTime, endDateTime)
query = "select * from employee where joining_date between :1 and :2"
cur = con.cursor()
cur.execute(query, parameters)
Tried the TO_DATE() function and Date'' qualifiers. Still no result for Between or >= operator. Noteworthy is that < operator works. I also got the same query and tried in a sql client, and the query returns results. Code:
#returns no rows:
query = "select * from employee where joining_date >= TO_DATE('" + startDateTime.strftime("%Y-%m-%d") + "','yyyy-mm-dd')"
cur = con.cursor()
cur.execute(query)
#tried following just to ensure that some query runs fine, it returns results:
query = query.replace(">=", "<")
cur.execute(query)
Any pointers about why the between and >= operators are failing for me? (my second approach was in line with the answer in Oracle date comparison in where clause but still doesn't work for me)
I am using python 3.4.3 and used cx_Oracle 5.3 and 5.2 with oracle client 11g on windows 7 machine
Assume that your employee table contains the field emp_id and the row with emp_id=1234567 should be retrieved by your query.
Make two copies of your a program that execute the following queries
query = "select to_char(:1,'YYYY-MM-DD HH24:MI:SS')||' >= '||to_char(joining_date,'YYYY-MM-DD HH24:MI:SS')||' >= '||to_char(:2,'YYYY-MM-DD HH24:MI:SS') resultstring from employee where emp_id=1234567"
and
query="select to_char(joining_date,'YYYY-MM-DD HH24:MI:SS')||' >= '||to_char(TO_DATE('" + startDateTime.strftime("%Y-%m-%d") + "','yyyy-mm-dd'),'YYYY-MM-DD HH24:MI:SS') resultstring from employee where emp_id=1234567"
Show us the code and the value of the column resultstring
You are constructing SQL queries as strings when you should be using parameterized queries. You can't use parameterization to substitute the comparison operators, but you should use it for the dates.
Also, note that the referenced answer uses the PostgreSQL parameterisation format, whereas Oracle requires you to use the ":name" format.

Resources