mySQL - Get last added ID [duplicate] - java

This question already has answers here:
How to get the insert ID in JDBC?
(14 answers)
Closed 4 years ago.
Im a new programmer (just started on my programmer education).
Im trying to set my "tempVenueId" attribute with the last ID in my SQL DB: (in this case idvenue = 12)
Table name: venue
idvenue | name | address
-------------------------------
1 | Khar | 5
2 | SantaCruz | 3
3 | Sion | 2
4 | VT | 1
5 | newFort | 3
6 | Bandra | 2
7 | Worli | 1
8 | Sanpada | 3
9 | Joe | 2
10 | Sally | 1
11 | Elphiston | 2
12 | Currey Road | 1
My code:
Private int tempVenueId;
SqlRowSet rs1 = jdbc.queryForRowSet("SELECT MAX(idvenue) FROM venue;");
while(rs1.next())tempVenueId = rs1.getInt(0);
/*I have also tried with "while(rs1.next())tempVenueId = rs1.getInt(1);"
*/
Still it does not work I get this when I run debug mode in intelliJ:
tempVenueId = 0

The index is from 1 rather than 0,so two ways to solve it:
while(rs1.next()){
tempVenueId = rs1.getInt(1);
break;
};
or
SqlRowSet rs1 = Jdbc.queryForRowSet("SELECT MAX(idvenue) as value FROM venue;");
while(rs1.next()){
tempVenueId = rs1.getInt("value");
break;
}

Solved - This solution was alot easier.... (I think).
String sql = "SELECT LAST_INSERT_ID();";
SqlRowSet rs = Jdbc.queryForRowSet(sql);
rs.next();
Venue VN = new Venue(rs.getInt(1));
tempVenueId = VN;
Now i get the last AUTO INCREMENTET ID from DB

Related

What is wrong in this Java JDBC program?

What is wrong in this Java JDBC program?
I have written a method that takes a ResultSet and prints all of its records.
My SQL query is:
Set #counter := 0, #counterQty := 0, #counterAvb := 0, #counterIss := 0, #counterRep := 0 ,#counterDes := 0;
Select *
From (SELECT
(Select (#counter := (#counter + 1) ) ) 'Sr.No.',
testt.BookName,
testt.BookQty,
testt.Code,
testt.Available,
testt.Issued,
testt.Repair,
testt.Destroyed,
(#counterQty := #counterQty + testt.BookQty ) TotalQty,
(#counterAvb := #counterAvb + testt.Available ) TotalAvb,
(#counterIss := #counterIss + testt.Issued ) TotalIss,
(#counterRep := #counterRep + testt.Repair ) TotalRep,
(#counterDes := #counterDes + testt.Destroyed ) TotalDest
From (Select a.b_name BookName, a.b_qty BookQty, a.b_acc_id Code,
SUM(case when b.status='A' then 1 else 0 end) as Available,
SUM(case when b.status='I' then 1 else 0 end) as Issued,
SUM(case when b.status='R' then 1 else 0 end) as Repair,
SUM(case when b.status='D' then 1 else 0 end) as Destroyed
From tbl_book_info a left join tbl_books b on a.b_acc_id = b.accid
GROUP BY a.b_name, a.b_qty, a.b_acc_id order by a.b_acc_id
)testt
)Main;
When I am executing this query in MySQL Workbench, it returns:
+--------+--------------+---------+-------+-----------+--------+--------+-----------+----------+----------+----------+----------+-----------+
| Sr.No. | BookName | BookQty | Code | Available | Issued | Repair | Destroyed | TotalQty | TotalAvb | TotalIss | TotalRep | TotalDest |
+--------+--------------+---------+-------+-----------+--------+--------+-----------+----------+----------+----------+----------+-----------+
| 1 | Java book | 3 | 10001 | 0 | 0 | 1 | 2 | 3 | 0 | 0 | 1 | 2 |
| 2 | Cpp Book | 5 | 10002 | 3 | 1 | 0 | 1 | 8 | 3 | 1 | 1 | 3 |
| 3 | Cpp 1.17 | 5 | 10003 | 3 | 1 | 0 | 1 | 13 | 6 | 2 | 1 | 4 |
| 4 | Visual Basic | 4 | 10004 | 4 | 0 | 0 | 0 | 17 | 10 | 2 | 1 | 4 |
+--------+--------------+---------+-------+-----------+--------+--------+-----------+----------+----------+----------+----------+-----------+
4 rows in set (0.25 sec)
But when I am executing this query in Java and printing all data of ResultSet, it returns like:
1 2 3 4 5 6 7 8 9 10 11 12 13
+--------+--------------+---------+-------+-----------+--------+--------+-----------+----------+----------+----------+----------+-----------+
| Sr.No. | BookName | BookQty | Code | Available | Issued | Repair | Destroyed | TotalQty | TotalAvb | TotalIss | TotalRep | TotalDest |
+--------+--------------+---------+-------+-----------+--------+--------+-----------+----------+----------+----------+----------+-----------+
0 Cpp 1.17 5 10003 3 1 0 1 0 0 0 0 0
0 Cpp Book 5 10002 3 1 0 1 0 0 0 0 0
0 Java book 3 10001 0 0 1 2 0 0 0 0 0
0 Visual Basic 4 10004 4 0 0 0 0 0 0 0 0
+--------+--------------+---------+-------+-----------+--------+--------+-----------+----------+----------+----------+----------+-----------+
My question is:
Why it is giving zero (0) for column 1,9,10,11,12 and 13
Tables structure
create table if not exists tbl_book_info(
b_acc_id int(5) not null auto_increment,
b_name varchar(50) not null,
b_qty int(2) not null,
b_type varchar(30) not null,
b_auth1 varchar(50) not null,
b_auth2 varchar(50),
b_pub varchar(50) not null,
b_pages int(4) not null,
b_rack int(5) not null,
b_price Decimal(6,2) not null,
b_about text,
primary key(b_acc_id)
);
create table if not exists tbl_books(
accid int(5) references tbl_book_info.b_acc_id,
accno int(3),
status varchar(1) default "A",
primary key(accid,accno)
);
My code to print this:
Connection con = getDbConnObj();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery( sql );
printRsLast(rs);
public void printRsLast(ResultSet rs){
/* +---1----+-----2--------+----3----+--4----+-----5-----+----6---+---7----+-----8-----+-----9----+----10----+----11----+----12----+-----13----+
| Sr.No. | BookName | BookQty | Code | Available | Issued | Repair | Destroyed | TotalQty | TotalAvb | TotalIss | TotalRep | TotalDest |
rs= +--------+--------------+---------+-------+-----------+--------+--------+-----------+----------+----------+----------+----------+-----------+
| 1 | Java book | 3 | 10001 | 1 | 0 | 0 | 2 | 3 | 1 | 0 | 0 | 2 |
|...........................................................................................................................................|
|...........................................................................................................................................|
|...........................................................................................................................................|
+--------+--------------+---------+-------+-----------+--------+--------+-----------+----------+----------+----------+----------+-----------+ */
String separator = " ";
try{
rs.beforeFirst();
int n=0;
p("$$$ RS Attr. are : \n\n Sr.No. | BookName | BookQty | Code | Available | Issued | Repair | Destroyed | TotalQty | TotalAvb | TotalIss | TotalRep | TotalDest , Row are...\n");
while(rs.next()){
n++;
String nm , m;
m = rs.getInt(1)+ separator + rs.getString(2)+ separator + rs.getInt(3)+ separator + rs.getInt(4)+ separator + rs.getInt(5)+ separator + rs.getInt(6)+ separator + rs.getInt(7)+ separator + rs.getInt(8)+ separator + rs.getInt(9)+ separator +
rs.getInt(10)+ separator + rs.getInt(11)+ separator + rs.getInt(12)+ separator + rs.getInt(13);
p(m+"\n");
}
p("\nTotal Rows = "+n);
} catch(Exception e){
p("\n!!! Excep in 'printRsLast(ResultSet rs), msg = '"+e.getMessage());
}
}
public Connection getDbConnObj() {
// Creating 'Connection' class' Reference Variable ...
Connection con = null;
String url = "jdbc:mysql://localhost:3306/librarydb";
String dbUname = "root";
String dbPass = "";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection(url, dbUname, dbPass);
} catch (Exception e) {
con = null;
} finally {
return con;
}
}
I tried both the things ...
1)
sql = "Set #counter := 0...";
rs = st.execute(sql); // Execute this 'Set #counter...' Stmt first Than
sql = "Select * From...";
rs = st.executeQuery(sql); // Executing this 'Select * from...' Stmt to get the Tabular Data...
printRsLast(rs);
2)
sql = "Set #counter := 0...
....
....
)Main;"
rs = st.executeQuery(sql); // Executing these Entire Stmt to get the Tabular Data...
printRsLast(rs);
But Unfortunately , Both did not worked for me...
You haven't shown us how you've constructed the string sql in your Java code, so I'm going to have to guess.
It seems that sql contains your query from Select * onwards, without the line Set #counter := 0 .... I was able to reproduce your output if I set sql to this. Perhaps you've tried putting that Set line in the query as well and that generated an error so you took it out?
What you need to do instead is to execute the Set #counter := 0 ... line and then run the query. In other words, replace the lines
Connection con = getDbConnObj();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery( sql );
printRsLast(rs);
with
Connection con = getDbConnObj();
Statement st = con.createStatement();
st.execute("Set #counter := 0 ...");
ResultSet rs = st.executeQuery( sql );
printRsLast(rs);
I made this modification to your code and it generated the output you wanted.

Oracle query to filter and sort table based on values in child table

I am using Oracle 11g, and I have tables with data and structure as follows:
TABLE1_PARENT:
-------------------
PID | Name | Age |
-------------------
1 | Mark | 35 |
2 | Jane | 40 |
3 | Agatha | 45 |
-------------------
TABLE2_CHILD
==============================================
CID | Name | Age | Class | House | PID |
----------------------------------------------
1 | John | 7 | 3 | Red | 1 |
2 | Marie | 5 | 1 | Yellow| 2 |
3 | Petra | 6 | 2 | Green | 3 |
4 | Taylor | 8 | 4 | Blue | 2 |
5 | Lean | 9 | 5 | Red | 2 |
6 | Justin | 7 | 3 | Yellow| 3 |
7 | Arianna | 5 | 1 | Blue | 3 |
8 | Brendon | 6 | 2 | Green | 3 |
9 | Shawn | 7 | 3 | Red | 1 |
----------------------------------------------
For a single condition, the query is simple:
SELECT * FROM TABLE1_PARENT WHERE PID IN (SELECT PID FROM TABLE2_CHILD WHERE AGE=7);
which will result in the following result:
TABLE1_PARENT:
-------------------
PID | Name | Age |
-------------------
1 | Mark | 35 |
3 | Agatha | 45 |
-------------------
However, if I want to fetch the list of parents whose children are of age=7 and belong to house='GREEN', if I write a query as below:
SELECT * FROM TABLE1_PARENT WHERE PID IN (SELECT PID FROM TABLE2_CHILD WHERE AGE=7 AND house='GREEN');
I would get no results.
I am expecting the result to be :
TABLE1_PARENT:
-------------------
PID | Name | Age |
-------------------
3 | Agatha | 45 |
-------------------
since Agatha has a child belonging to age=7, and a child belonging to house='GREEN'.
I was able to come up with a solution for a similar data structure using Java streams. I am trying to do the same using Oracle SQL.
List<Parent> filteredParents = parents.stream()
.filter(parent -> parent.getChildren().stream()
.anyMatch(child -> child.getAge().equals("7")) && parent.getChildren().stream()
.anyMatch(child -> child.getHouse().equalsIgnoreCase("Green")))
.collect(Collectors.toList());
I am expecting the query to give me a result where the conditions could match any of the children. Because, the filtering is happening at the Parent level.
Any help would be great. Thanks!
You can do it with EXISTS:
SELECT t.*
FROM TABLE1_PARENT t
WHERE t.PID IN (
SELECT PID FROM TABLE2_CHILD WHERE AGE=7
) AND EXISTS (
SELECT 1 FROM TABLE2_CHILD WHERE PID = t.PID AND House = 'Green'
)
The problem with your query is that it tries to apply both conditions in the same row inside TABLE2_CHILD. But this is not what you want.
You want the parent ids for which children rows have AGE = 7 and there is a row inside TABLE2_CHILD with House = 'Green'.
You could use EXISTS for both conditions, which may be more efficient:
SELECT t.*
FROM TABLE1_PARENT t
WHERE EXISTS (
SELECT 1 FROM TABLE2_CHILD WHERE PID = t.PID AND AGE=7
) AND EXISTS (
SELECT 1 FROM TABLE2_CHILD WHERE PID = t.PID AND House = 'Green'
)
or with conditional aggregation by grouping the child table by PID:
SELECT * FROM TABLE1_PARENT
WHERE PID IN (
SELECT PID
FROM TABLE2_CHILD
GROUP BY PID
HAVING
SUM(CASE WHEN Age = 7 THEN 1 ELSE 0 END) > 0
AND
SUM(CASE WHEN House = 'Green' THEN 1 ELSE 0 END) > 0
)
You are not getting output because in your TABLE2_CHILD, there is no child whose age is 7 in the green house. For your expected result, the query should be:
SELECT * FROM TABLE1_PARENT WHERE PID IN (SELECT PID FROM TABLE2_CHILD WHERE AGE=7) AND PID IN (SELECT PID FROM TABLE2_CHILD WHERE house='GREEN');
If you want to get the parent who have a child with age = 7, and the same child belongs to house=GREEN, use the query you already wrote:
SELECT * FROM TABLE1_PARENT WHERE PID IN (SELECT PID FROM TABLE2_CHILD IF AGE=7 AND house='GREEN');
If you want to get the parent whose children either has age=7 or house=GREEN or both, use
SELECT * FROM TABLE1_PARENT WHERE PID IN (SELECT PID FROM TABLE2_CHILD IF AGE=7 OR house='GREEN');

Calculate/Determine Hours for Nightshift in mysql

Here is the table for the employee's logs:
And what I want is to generate the time ins and time out of employees. like this:
Can anyone help me for this? Any added logic or algorithm will be accepted.
This is one way. And it will work for day/night any shifts, provided, the first min(datetime) represent IN.
Rextester Sample
select t.enno
,max(datetime) as time_out
,min(datetime) as time_in
,time_to_sec(timediff(max(datetime), min(datetime) )) / 3600
as No_of_hours
from
(
SELECT
floor(#row1 := #row1 + 0.5) as day,
t.*
FROM Table4356 t,
(SELECT #row1 := 0.5) r1
order by t.datetime
) t
group by t.day,t.enno
;
Output
+------+---------------------+---------------------+-------------+
| enno | time_out | time_in | No_of_hours |
+------+---------------------+---------------------+-------------+
| 6 | 16.05.2017 06:30:50 | 15.05.2017 18:30:50 | 12,0000 |
| 6 | 17.05.2017 05:30:50 | 16.05.2017 18:10:50 | 11,3333 |
+------+---------------------+---------------------+-------------+
Explanation:
SELECT
floor(#row1 := #row1 + 0.5) as day,
t.*
FROM Table4356 t,
(SELECT #row1 := 0.5) r1
order by t.datetime
This query uses sequence to increment #row1 with 0.5, so you will get 1 1.5 2 2.5. Now if you just get the integer part of with with floor, you will generate sequece like 1 1 2 2. So this query will give you this output
+-----+------+---------------------+
| day | enno | datetime |
+-----+------+---------------------+
| 1 | 6 | 15.05.2017 18:30:50 |
| 1 | 6 | 16.05.2017 06:30:50 |
| 2 | 6 | 16.05.2017 18:10:50 |
| 2 | 6 | 17.05.2017 05:30:50 |
+-----+------+---------------------+
Now you can group by day and get max and min time.

MySQL query to fetch list of data using logical operations

The following are the list of different kinds of books that customers read in a library. The values are stored with the power of 2 in a column called bookType.
I need to fetch list of books with the combinations of persons who read
only Novel Or only Fairytale Or only BedTime Or both Novel + Fairytale
from the database with logical operational query.
Fetch list for the following combinations :
person who reads only novel(Stored in DB as 1)
person who reads both novel and fairy tale(Stored in DB as 1+2 = 3)
person who reads all the three i.e {novel + fairy tale + bed time} (stored in DB as 1+2+4 = 7)
The count of these are stored in the database in a column called BookType(marked with red in fig.)
How can I fetch the above list using MySQL query
From the example, I need to fetch users like novel readers (1,3,5,7).
The heart of this question is conversion of decimal to binary and mysql has a function to do just - CONV(num , from_base , to_base );
In this case from_base would be 10 and to_base would be 2.
I would wrap this in a UDF
So given
MariaDB [sandbox]> select id,username
-> from users
-> where id < 8;
+----+----------+
| id | username |
+----+----------+
| 1 | John |
| 2 | Jane |
| 3 | Ali |
| 6 | Bruce |
| 7 | Martha |
+----+----------+
5 rows in set (0.00 sec)
MariaDB [sandbox]> select * from t;
+------+------------+
| id | type |
+------+------------+
| 1 | novel |
| 2 | fairy Tale |
| 3 | bedtime |
+------+------------+
3 rows in set (0.00 sec)
This UDF
drop function if exists book_type;
delimiter //
CREATE DEFINER=`root`#`localhost` FUNCTION `book_type`(
`indec` int
)
RETURNS varchar(255) CHARSET latin1
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
begin
declare tempstring varchar(100);
declare outstring varchar(100);
declare book_types varchar(100);
declare bin_position int;
declare str_length int;
declare checkit int;
set tempstring = reverse(lpad(conv(indec,10,2),4,0));
set str_length = length(tempstring);
set checkit = 0;
set bin_position = 0;
set book_types = '';
looper: while bin_position < str_length do
set bin_position = bin_position + 1;
set outstring = substr(tempstring,bin_position,1);
if outstring = 1 then
set book_types = concat(book_types,(select trim(type) from t where id = bin_position),',');
end if;
end while;
set outstring = book_types;
return outstring;
end //
delimiter ;
Results in
+----+----------+---------------------------+
| id | username | book_type(id) |
+----+----------+---------------------------+
| 1 | John | novel, |
| 2 | Jane | fairy Tale, |
| 3 | Ali | novel,fairy Tale, |
| 6 | Bruce | fairy Tale,bedtime, |
| 7 | Martha | novel,fairy Tale,bedtime, |
+----+----------+---------------------------+
5 rows in set (0.00 sec)
Note the loop in the UDF to walk through the binary string and that the position of the 1's relate to the ids in the look up table;
I leave it to you to code for errors and tidy up.

How to select next record and previous record in SQLite?

I have been searching like forever
I am using min and max for the last and and first record but how do I get the next/ record? I have a column name rowid it is the pk and auto incremented by one every time a user registers
| rowid | Name |
| 1 | John |*
| 2 | Mark |
| 3 | Peter|
| 4 | Help |
so if I click the next button I wanted to select mark which is in rowid 2
| rowid | Name |
| 1 | John |
| 2 | Mark |*
| 3 | Peter|
| 4 | Help |
but if I click the next button twice I want to be in rowid 4
| rowid | Name |
| 1 | John |
| 2 | Mark |
| 3 | Peter|
| 4 | Help |*
how do I do that? by the way I don't have fixed rows since I have a registration function
so here's my code
JButton btnNextLast = new JButton(">>");
btnNextLast.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
String sQuery = "select * from accountinfo where rowid = (SELECT MAX(rowid) FROM accountinfo)";
PreparedStatement prst = connection.prepareStatement(sQuery);
ResultSet rs = prst.executeQuery();
lblSID.setText(rs.getString("sid"));
lblfirst.setText(rs.getString("last"));
lblLast.setText(rs.getString("first"));
lblmiddle.setText(rs.getString("middle"));
lblbirth.setText(rs.getString("birth"));
lblcontact.setText(rs.getString("contact"));
}catch(Exception qwe){
}
}
});
I've tried
select rowid
from accountinfo
where rowid >1
order by rowid
limit 1
but no luck
and if I remove order by rowid limit 1. It just show the next record which is 2 and never function again

Categories