sql : how can i execute two dependents queries? - java

I have 2 tables (table1, table2) table1 has a field id and table2 has a field id_eid that reference the id field of table1 as foreign key.
I have to delete from table1 all the rows that match a determinated criteria and then if these data are referenced in table2 delete the data from it too.
I do something like that, assuming con is the Connection object and autocommit is set to false on it.
String query1 = "delete from table2 where exists
(select * from table1 where someparameter = ? and table1.id = table2.id_eid)"
then i execute the first query1 using PreparedStatement.
then i have
String query2 = "delete from table1 where someparameter = ?
and exists (select * from table2 where table1.id = table2.id_eid)"
and i executed this with another PreparedStatment.
at the end i have the con.commit().
This doesn't work, i was thinking using autocommit to false the two queries was executed together but it is not, the second query deletes no rows, how can i do this ?
An important note, not all the rows in table1 have a referenced row in table2.
Thanks

You could always query the data to delete first, then delete it second:
1) Select ID from table1 where <criteria>
2) Select ID from table2 where <criteria>
3) Delete from table1 where ID in <results from (1)>
4) Delete from table2 where ID in <results from (2)>

If you
"have to delete from table1 all the rows that match a determinated criteria"
I think String query2 must be
String query2 = "delete from table1 where someparameter = ?"

Related

Oracle update with join in execute update jsp

I want to update column1 of table1 by checking the condition with column2 of table1 and column2 of table2.
I just get the error of missing right parenthesis.
I just check the ID of both tables (ID is foreign key to another table) and check the activation code came from query string and if they match I just update the value of status as approve
String s = "Approve";
stmt.executeUpdate("UPDATE
( SELECT Approval.STATUS AS st
FROM Approval
JOIN Activity
ON Activity.userid = Approval.id
WHERE Activity.activationcode =
'"+activationcode+"') as up SET up.st = '"+s+"'");
Replace your update table string with below and it should work
UPDATE
(SELECT
Approval.STATUS AS st
FROM
Approval JOIN Activity ON Activity.userid = Approval.id
WHERE
Activity.activationcode = '"+activationcode+"'
) up
SET up.st = '"+s+"'
In your query you are trying to update APPROVAL and UP tables both that is why you are getting an error

Insert data to mysql database if not exist

I'm using java and I want to insert to mysql database a data if not exist, Also I want to update that data if exist. but I couldn't find mysql command for this.
I found this code for Insert but this is not what I want
INSERT INTO contacts
(contact_id, contact_name)
SELECT supplier_id, supplier_name
FROM suppliers
WHERE EXISTS (SELECT *
FROM orders
WHERE suppliers.supplier_id = orders.supplier_id);
For update, I found this code. but this is not what I want.
UPDATE suppliers
SET supplier_name = (SELECT customers.customer_name
FROM customers
WHERE customers.customer_id = suppliers.supplier_id)
WHERE EXISTS (SELECT *
FROM customers
WHERE customers.customer_id = suppliers.supplier_id);
What I want to do is something like this
UPDATE student SET student_score = 20 where student_id = 1 WHERE EXIST ( select * from student where student_id = 1;
You can use:
insert into table_name (id, name, firstname) values(1, "Sessi", "Brahim") on duplicate key update name=values(name), firstname=values(firstname)
Adapt it to your query.

Disable certain records while fetching records from a database table in Android

Im working with SQLite db in android and am stuck making a particular query:
I have a Table 1 with some email ids and I have another Table 2 with email ids and the usernames corresponding to those ids. From Table 2 I need to send only those emailid/usernames which are not present in Table 1. I want to do this using Cursor in android, something like:
Cursor cursor = getReadableDatabase().query(
MY_TABLE,
new String[] {ID},
EMAIL_ID +" = ?",
new String[]{email_id},
null,
null,
null);
The prerequisites are:
I don't want to use delete from Table 2
I don't want to create extra column in Table 2.
Use NOT IN with a subselect to filter out results in your query. For example:
SELECT emailid,username FROM table2 WHERE emailid NOT IN (SELECT emailid FROM table1)
Use rawQuery() for performing such raw SQL queries instead of query() which builds the SQL for you.
Example:
sqlite> create table table2(emailid,username);
sqlite> create table table1(emailid);
sqlite> insert into table1 select 'a#b.c';
sqlite> insert into table1 select 'a#b.c.d';
sqlite> insert into table2 select 'a#b.c.d','abcd';
sqlite> insert into table2 select 'a#b.c.d.e','abcde';
sqlite> SELECT emailid,username FROM table2 WHERE emailid NOT IN (SELECT emailid FROM table1);
a#b.c.d.e|abcde
Since #m0skit0 is insistent in his comments, let's demonstrate his query with the same data:
sqlite> SELECT t2.emailid, t2.username FROM table1 t1, table2 t2 WHERE t1.emailid <> t2.emailid;
a#b.c.d|abcd
a#b.c.d.e|abcde
a#b.c.d.e|abcde
You just need to join both tables over emailid and username field.
SELECT t2.emailid, t2.username FROM table1 t1, table1 t1a, table2 t2 WHERE t1.emailid <> t2.emailid AND t1a.username <> t2.username
This will get you all rows in table2 whose emailid or username does not exist in table1.
Also you need to use rawQuery method instead if more than one table in your SQL query:
private static final String QUERY = "SELECT t2.emailid, t2.username FROM table1 t1, table2 t2 WHERE t1.emailid <> t2.emailid AND t1.username <> t2.usernam";
final Cursor cursor = getReadableDatabase().rawQuery(QUERY, new String[0]);

How to select last inserted 5 record from table using JPA with Hibernate

How to select last inserted 5 record from table using JPA with Hibernate?
public List<Sample> getAgencyChangeLastFiveRecords(){
return (ArrayList<Sample>) createQuery(
"select * from ( select * from sample order by id desc) where rownum<=5 order by rownum desc"
);
}
This is not working. What would be the corresponding HQL query?
may be you can try below
String hql="from Sample order by id desc"
Query.setMaxResults(5)

problem in setString method.in retrieving data from the table

i have two tables "Table1" with columns user_name,Password and course ID and another table "course" with columns course_id,course_name.I have used the following code to display the course ID from Table1 according to the user_name received from the login page.using ResultSet rs1.now i want to retrieve the course_name from the table "course" according to the course ID receieve from "Table1".for that in the second query pstmt2.setString(1, ); what parameter i should use to get the course_id value from the previous query
HttpSession sess=request.getSession();
String a=(String)sess.getAttribute("user");
String b=(String)sess.getAttribute("pass");
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:ggg");
Statement st = con.createStatement();
String query="select * from Table1 where user_name=?";
PreparedStatement pstmt=con.prepareStatement(query);
pstmt.setString(1,a);
ResultSet rs1=pstmt.executeQuery();
while(rs1.next())
out.println("<h3>COURSE ID: "+rs1.getString("course ID")+"<h3>");
String query2="SELECT * from course where course_id=?";
PreparedStatement pstmt2=con.prepareStatement(query2);
pstmt2.setString(1,);
ResultSet rs2=pstmt2.executeQuery();
while(rs2.next())
{
out.println("<h3>course name: "+rs2.getString("course_name")+"<h3>");
}
why do you go for two turns of database hit, even though you created one time connection object.
modify the query as below
SELECT * from course where course_id = (select course_id from Table1 where user_name=?);
from this query you noneed to give input of courseid also.
No need to hit database twice to get the results that you need. use the query
Select table1.course_id, course.course_name from table1, course where table1.course_id=course_id and table1.user_name=?
This should set the course_id parameter:
pstmt2.setString(1,rs1.getString("course_id"));
Or, as I see the "course_id" column may have a different name in "Table1":
pstmt2.setString(1,rs1.getString("course ID"));
As the other post mentioned there's no need to go to another set of query. Try this example query:
SELECT course.course_id, course.course_name
FROM table1 t1
INNER JOIN course c
ON t1.course_id = c.course_id
WHERE t1.user_name = ?;
Now if you insist your coding the parameter o your pstmt2.setString(1,); is:
pstmt2.setString(1,rs1.getString("course_id")); //or course ID defending on your column name

Categories