QSqlQuery Postgres multiple select - postgresql

I have a query which contains two part. First part call function which creates a temporary table, second part select data from this table.
SELECT create_data_slice(15962, NULL, ARRAY[[15726]]);
SELECT
AK."15962_15726" as AK_NAME
FROM
t15962 AK
GROUP BY
AK."15962_15726;"
If I execute this query in PgAdmin, it turns right result with data. But if I execute it in Qt:
QSqlDatabase db = store->get_db();
QSqlQuery query(db);
query.exec(sql);
it executes only the first part (create temporary table), but do not execute second part and do not return data.

You can use a transaction like this:
QSqlDatabase::database().transaction();
QSqlQuery query;
query.exec("SELECT create_data_slice(15962, NULL, ARRAY[[15726]]);");
if (query.next())
{
int employeeId = query.value(0).toInt();
query.exec("SELECT AK."15962_15726" as AK_NAME FROM t15962 AK GROUP BY AK."15962_15726;");
while(query.next())
{
qDebug() << query.value().toString(); ///or what you want to do with data
}
}
QSqlDatabase::database().commit();

Related

Why am I getting error 17410 end of data on my rest api when I add a parameter to the query

I have ORDS 21 installed in a local 19c oracle database. I have created a stored procedure to list all the departments from the dept table with a cursor that lists the employees from the emp table. If I just list all departments and their employees the api works fine, but if I add a parameter to the query to specify which department, I get an error 17410 no data left .
Both queries are backed by plsql stored procedures. I have created many stored procedures using this same format with parameters and nested cursors before without a problem.
MWE for query that works:
create or replace procedure get_dept
as
l_cur sys_refcursor;
begin
open l_cur for
select d.deptno,d.dname,
cursor (select e.empno,e.ename
from emp e
where e.deptno = d.deptno
order by e.deptno,e.empno
) as employees
from dept d
order by d.deptno;
-- return the resultset in json format
apex_json.open_object;
apex_json.write('emps',l_cur);
apex_json.close_object;
end get_dept;
/
MWE for query that does not work:
create or replace procedure get_dept1
(
p_dept_no in varchar2
) as
l_cur sys_refcursor;
begin
open l_cur for
select d.deptno,d.dname,
cursor (select e.empno,e.ename
from emp e
where e.deptno = d.deptno
order by e.deptno,e.empno
) as employees
from dept d
where d.deptno = to_number(p_dept_no)
order by d.deptno;
-- return the resultset in json format
apex_json.open_object;
apex_json.write('emps',l_cur);
apex_json.close_object;
end get_dept1;
/

sqlalchemy to create temporary table

I created a temporary table with sqlalchemy (with an underlying postgres database) that is going to be joined with a database table. However, in some cases when a value is empty '' then postgres throws the error:
failed to find conversion function from unknown to text
SqlAlchemy assembles everything to the following context
[SQL: 'WITH temp_table AS \n(SELECT %(param_1)s AS id, %(param_2)s AS email, %(param_3)s AS phone)\n SELECT campaigns_contact.id, campaigns_contact.email, campaigns_contact.phone \nFROM campaigns_contact JOIN temp_table ON temp_table.id = campaigns_contact.id AND temp_table.email = campaigns_contact.email AND temp_table.phone = campaigns_contact.phone'] [parameters: {'param_1': 83, 'param_2': '', 'param_3': '+1234567890'}]
I assemble the temporary table as follows
stmts = []
for row in import_data:
row_values = [literal(row[value]).label(value) for value in values]
stmts.append(select(row_values))
subquery = union_all(*stmts)
subquery = subquery.cte(name="temp_table")
The problem seems to be the part here
...%(param_2)s AS email...
which after replacing the param_2 results in
...'' AS email...
which will cause the error mentioned above.
One way to solve the issue is to perform a cast
...''::text AS email...
However, I don't know how to perform ::text cast with sqlalchemy!?

Delete statement not executed in postgresql

I am creating a transaction where I want to update a user in one table and delete some data in another that belongs to that user. But only the first query is executed, not the second one. In the delete statement in the second query code is a comma-separated std::string.
pqxx::connection c(connectionString);
try {
pqxx::work w(c);
pqxx::result r;
c.prepare("user", "update user set started = null, finished = null, task = $1 where id = $2");
r = w.prepared("user")(task)(email).exec();
c.prepare("belongings", "delete from belongings where id in " \
"(select id from info where code in ($1) and id = $2)");
r = w.prepared("belongings")(code)(id).exec();
w.commit();
}
I read this SO-thread that explain how to run multiple queries before commit(). So I must be making a mistake in the second delete statement but can't find the reason.
The code parameter is interpreted as a single literal. You can try to use the alternative syntax of any(array expression), e.g.:
code = "{abc,def}"; // instead of code = "'abc','def'"
...
c.prepare("belongings", "delete from belongings where id in " \
"(select id from info where code = any ($1) and id = $2)");
r = w.prepared("belongings")(code)(id).exec();

DB2 Query : insert data in history table if not exists already

I have History table and transaction table.....and reference table...
If status in reference table is CLOSE then take those record verify in History table if not there insert from transaction table..... wiring query like this .... checking better one... please advice.. this query can be used for huge data ?
INSERT INTO LIB1.HIST_TBL
( SELECT R.ACCT, R.STATUS, R.DATE FROM
LIB2.HIST_TBL R JOIN LIB1.REF_TBL C
ON R.ACCT = C.ACCT WHERE C.STATUS = '5'
AND R.ACCT NOT IN
(SELECT ACTNO FROM LIB1.HIST_TBL)) ;
If you're on a current release of DB2 for i, take a look at the MERGE statement
MERGE INTO hist_tbl H
USING (SELECT * FROM ref_tbl R
WHERE r.status = 'S')
ON h.actno = r.actno
WHEN NOT MATCHED THEN
INSERT (actno,histcol2, histcol3) VALUES (r.actno,r.refcol2,r.refcol3)
--if needed
WHEN MATCHED
UPDATE SET (actno,histcol2, histcol3) = (r.actno,r.refcol2,r.refcol3)

update data using loop in sql syntax

I work with postgreSQL
I want to update email of all my users using sql
I have a table named user that contains 500 users,
so I think that I should use a loop in my sql syntax
For example when the table contains 4 users, I want the email for these users to become :
user1#hotmail.fr
user2#hotmail.fr
user3#hotmail.fr
user4#hotmail.fr
in java it should be like this
String newValue=null;
for(int i=0;i<list.size();i++)
{
newValue="user"+i+"#hotmail.fr";
// make update
}
I think that I should use plsql syntax
updated :
I try without success with this code :
BEGIN
FOR r IN SELECT * from user_
LOOP
NEXT r;
UPDATE user_ SET emailaddress = CONCAT('user',r,'#hotmail.fr')
END LOOP;
END
I solved the problem using this query :
UPDATE user_ SET emailaddress='user' || col_serial || '#hotmail.fr' FROM
(SELECT emailaddress, row_number() OVER ( ORDER BY createdate) AS col_serial FROM user_ ORDER BY createdate) AS t1
WHERE user_.emailaddress=t1.emailaddress