count similar rows of one table in jdbc - java

I'm trying to count same values from one column of the table and return the value and counter, for example: value 1 repeat 3 time, value 2 repeat 2 time, ...
So far my program can store all value of desired column in an array. My problem is I don't know how to compare each value with other value. I know I need a counter and maybe one more array. So I stuck in If condition.
try{
Statement stmt = conn.createStatement();
//Statement stmt1 = conn.createStatement();
ResultSet rset = stmt.executeQuery( "SELECT N_REGIONKEY FROM NATION " );
List N_REGIONKEY = new ArrayList ();
while (rset.next()){
N_REGIONKEY.add(rset.getInt("N_REGIONKEY"));
if (rset.next ==N_REGIONKEY){
.
.
.
}
//System.out.println(N_REGIONKEY);
}
}
This is new version of what I wrote with your help, still the answer is not what it should be..
try{
System.out.println("counting rows in NATION table");
Statement stmt = conn.createStatement();
// Statement stmt1 = conn.createStatement();
ResultSet rset = stmt.executeQuery( "SELECT N_REGIONKEY FROM NATION " );
ArrayList N_REGIONKEY = new ArrayList ();
while (rset.next()){
N_REGIONKEY.add(rset.getInt("N_REGIONKEY"));
int occurrences = 0;
for (int i = 0; i<N_REGIONKEY.size();i++)
{
occurrences = Collections.frequency(N_REGIONKEY,N_REGIONKEY.get(i) );
System.out.println("There is " + occurrences + "occurrences for " + N_REGIONKEY.get(i));
}

Try to count by sql query, not by array
select N_REGIONKEY, count(N_REGIONKEY) as 'COUNT'
FROM NATION
group by N_REGIONKEY

int occurrences = 0;
for (int i = 0; i<N_REGIONKEY.size();i++){
occurrences = Collections.frequency(REGIONKEY, REGIONKEY.get(i));
System.out.println("There is " + ocurrences "ocurrences for " + N_RegionKey.get(i));
}

Thanks every one for your helps.Finally, I wrote this program without group by(even-though I know it's much slower). This ones has the same result as with "group by".
try{
System.out.println("counting simillar rows in NATION table");
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery( "SELECT N_REGIONKEY FROM NATION " );
ArrayList N_REGIONKEY = new ArrayList ();
int[] MyCounter = new int[5];
while (rset.next()){
MyCounter[rset.getInt("N_REGIONKEY")] ++;
}
for (int i = 0; i<5;i++){
if (MyCounter[i] > 0) {
System.out.println("There is " + MyCounter[i] + " ocurrences for " + i);
}

Related

sqlite query using java

I'm working on shifts manager program which calculates monthly salary and etc.
the program based on SQLite database which keeps getting updated by the user input.
my question is , how can i use the SQLite function in java to retrieve information, lets say monthly salary in one command (i know i can use " select sum(tips) between date1 and date2",but how can i get the function result inside a variable?)
so far i've created a function which gets two dates and retrieves all the shifts salary between these dates and summarise them with ResultSet.
here's my code:
public static String tipsMade(String date1, String date2){
Connection c = null;
Statement stmt = null;
ResultSet rs = null;
String ans= null;
int sum = 0;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Gil\\test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
rs = stmt.executeQuery("select tips from shifts where fulldate between "+"'"+date1+"'"+"and " +"'"+date2+"'"+ ";");
while(rs.next()){
sum += rs.getInt("tips");
}
ans = Integer.toString(sum);
//
//close connections and etc
stmt.close();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
return ans;
}
I edited your code.
Note that in case you select the sum of the tips, the column name changes. You also get only one row with one column as your result, so you should not need the while loop anymore.
The sum of the tips is now saved in the variable sum
public static String tipsMade(String date1, String date2){
Connection c = null;
Statement stmt = null;
ResultSet rs = null;
String ans= null;
int sum = 0;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Gil\\test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
rs = stmt.executeQuery("select sum(tips) from shifts where fulldate between "+"'"+date1+"'"+"and " +"'"+date2+"'"+ ";");
while(rs.next()){
sum = rs.getInt("sum(tips)");
}
ans = Integer.toString(sum);
//
//close connections and etc
stmt.close();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
return ans;
}

Display nth highest value if matched with comboBox value

I am using cosine similarity function to compare the value between user input and the data in SQL. The highest value will be retrieved and displayed.
However, k is the value getting from comboBox and it is hard constraints which mean they need to be fulfilled. So I have set it to something like:
The highest value found in index X . Before display, it will check whether day is equal to k. If not, it will look at the second highest and so on until day is equal to k.
But this doesn't make sense at all. If day is equal to k only when it is in the ninth highest value, then I need to set until ninth highest value? Is there any method can solve this?
private void pick_highest_value_here_and_display(ArrayList<Double> value,
int k) throws Exception {
// TODO Auto-generated method stub
double aa[] = value.stream().mapToDouble(v -> v.doubleValue()).toArray();
double highest = Double.MIN_VALUE;
double secHighest = Double.MIN_VALUE;
int highestIndex = 0;
for (int i = 0; i < aa.length; i++) {
if (aa[i] > highest) {
highest = aa[i];
highestIndex = i;
}
}
System.out.println("The highest value is " + highest + "");
System.out.println("It is found at index " + highestIndex + "");
String sql = "Select Day from menu where ID =?";
DatabaseConnection db = new DatabaseConnection();
Connection conn = db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, highestIndex);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
int aaa = rs.getInt("Day");
System.out.println(aaa);
if (aaa == k) // check whether aaa(day) is equal to k (comboBox)
{
String sql1 = "Select * from placeseen where ID =?";
DatabaseConnection db1 = new DatabaseConnection();
Connection conn1 = db1.getConnection();
PreparedStatement ps1 = conn1.prepareStatement(sql1);
ps1.setInt(1, highestIndex);
ResultSet rs1 = ps1.executeQuery();
if (rs1.next()) {
String a = rs1.getString("place1");
String bbb = rs1.getString("place2");
Tourism to = new Tourism();
to.setPlace1(a);
to.setPlace2(bbb);
DispDay dc = new DispDay();
dc.setVisible(true);
}
ps1.close();
rs1.close();
conn1.close();
} else // if not equal
{
int secIndex = 0;
for (int i = 0; i < aa.length; i++) {
if (aa[i] > secHighest) {
secHighest = aa[i];
secIndex = i;
}
}
System.out.println("The second highest value is " + secHighest + "");
System.out.println("It is found at index " + secIndex + "");
String sql2 = "Select Day from menu where ID =?";
DatabaseConnection db2 = new DatabaseConnection();
Connection conn2 = db2.getConnection();
PreparedStatement ps2 = conn.prepareStatement(sql2);
ps2.setInt(1, secIndex);
ResultSet rs2 = ps.executeQuery();
if (rs2.next()) {
int de = rs2.getInt("Day");
System.out.println(de);
if (de == k) {
String l = "Select * from placeseen where ID =?";
DatabaseConnection db3 = new DatabaseConnection();
Connection conn3 = db3.getConnection();
PreparedStatement ps3 = conn3.prepareStatement(l);
ps3.setInt(1, secIndex);
ResultSet rs3 = ps3.executeQuery();
if (rs3.next()) {
String a = rs3.getString("place1");
String bbb = rs3.getString("place2");
Tourism to = new Tourism();
to.setPlace1(a);
to.setPlace2(bbb);
DispDay dc = new DispDay();
dc.setVisible(true);
}
ps3.close();
rs3.close();
conn3.close();
}
}
}
ps.close();
rs.close();
conn.close();
}
}
Your code is somewhat difficult to understand, bit it sounds like you are trying to obtain the "highest" database value (in some sense) whose value matching some user input.
At the most basic level, consider constructing a basic query that looks like:
SELECT MAX(value column)
FROM menu
JOIN placeseen
ON (conditions)
WHERE (condition to ensure that data matches input)
If that's possible, it's a high-performance way to ensure that the data lines up between the tables and also matches the user input.

PostgreSQL MAX aggregate function applied to strings and Java resultset

Hello and thank you for reading my post.
I have a PostgreSQL table "t" with a column "c" which type is "character varying(32)".
Values in this column look like this: "2014100605".
I am using the "MAX()" aggregate function to retrieve the maximum value in this column.
SELECT MAX(c) AS max FROM t;
In Java, if I prepare the query above, get a "resultSet" object and send it the getString("max") message, I get max = null.
If I send it the getInt("max") method instead, I get the result I'm expecting, something like "2014100605".
Is this normal behavior?
Am I really allowed to do this or is it by chance I'm getting the expected result?
Is "MAX()" actually using the lexicographical order?
Best regards.
A bit of Java code:
s_preparedSqlQuery =
"SELECT MAX(quotinv_nro) AS quotinv_nro_max "
+ "FROM imw_quotation_invoice "
+ "WHERE quotinv_type = ? "
+ "AND quotinv_nro LIKE '" + s_quotinvDate + "%'";
preparedStatement = m_connection.prepareStatement(s_preparedSqlQuery);
preparedStatement.setString(1, s_quotinvType);
resultSet = preparedStatement.executeQuery();
if(resultSet != null)
{
if(resultSet.next())
{
// s_quotinvNroMax = resultSet.getString("quotinv_nro_max");
n_quotinvNroMax = resultSet.getInt("quotinv_nro_max");
// if(s_quotinvNroMax == null)
if(n_quotinvNroMax == 0)
{
n_nbQuotinvsThisSameDate = 0;
return n_nbQuotinvsThisSameDate;
}
else
{
s_quotinvNroMax = Integer.toString(n_quotinvNroMax);
n_length = s_quotinvDate.length();
s_currentMaxNro = s_quotinvNroMax.substring(n_length - 1);
n_nbQuotinvsThisSameDate = Integer.valueOf(s_currentMaxNro);
}
}
}
If you are hitting on a unique Id column....
int maxID = 0;
Statement s2 = con.createStatement();
s2.execute("SELECT MAX(UniqueId) FROM MyTable");
ResultSet rs2 = s2.getResultSet();
if (rs2.next())
{
maxID = rs2.getInt(1);
}
If you are hitting on any other non-key column....
int maxID = 0;
Statement s2 = con.createStatement();
s2.execute("SELECT MAX(ColumnValue) FROM MyTable");
ResultSet rs2 = s2.getResultSet();
while (rs2.next())
{
maxID = rs2.getInt(1);
}

java.sql.SQLException: ResultSet closed [duplicate]

This question already has answers here:
When is ResultSet closed?
(3 answers)
Closed 2 years ago.
I cant not do the further process because I get ResultSet closed while running this code. I am adding the value after 15 row of the sqlite database table and I want to find average value of 15 row and that should be store in ArrayList.
Here is the code:-
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully3");
stmt = c.createStatement();
rs = stmt
.executeQuery("SELECT TIME,BID,ASK FROM '" + title + "' ;");
System.out.println("Opened database successfully 20");
while (rs.next()) {
i++;
System.out.println(i);
if (i > 15) {
System.out.println("i am in");
List<String> stocklist = new ArrayList<String>();
String main = rs.getString(1);
System.out.println(rs.getString(1));
String s[] = main.split(" ", 2);
String date = s[0];
String time = s[1];
stocklist.add(date);
stocklist.add(time);
stocklist.add(df.format(rs.getFloat("BID")));
stocklist.add(df.format(rs.getFloat("ASK")));
rs1 = stmt
.executeQuery("SELECT ASK FROM '" + title + "' ;");
int j = 1;
while (rs1.next()) {
if (j < i) {
System.out.println(rs1.getFloat("ASK"));
avg = avg + rs1.getFloat("ASK");
}
j++;
}
rs1.close();
System.out.println("i am out");
avg = avg / 15;
changepercent = ((rs.getFloat("ASK") - avg) / avg) * 100;
stocklist.add(df.format(changepercent));
stocklist.add("ETE");
stocklist.add("HUN");
stocklist.add("ALU");
stocklist.add("ETE");
stocklist.add("HUN");
stocklist.add("ALU");
stocklist.add("ETE");
stocklist.add("HUN");
hntm.addRow(stocklist);
}
}
rs.close();
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
you should not reuse a Statement. When you create a new Query, you need so use a new Statement Object. Replace rs1 = stmt.executeQuery("SELECT ASK FROM '" + title + "' ;"); with rs1=c.createStatement().executeQuery("SELECT ASK FROM '" + title + "' ;");
This is not the answer for this question, but i was also having problem with java.sql.SQLException: ResultSet closed.
In my case the result from the query was empty and i was using SQLite, so the ResultSet returned closed.
PreparedStatement preparedStatement = connection.prepareStatement(sql);
ResultSet resultSet = preparedStatement.executeQuery();
// resultSet closed == didn't find anything
if(resultSet.isClosed())
return false;
I tested using PostgreSQL and ResultSet stay open even when query is empty. I didn't expect different behavior from different databases.
If anyone want to check my test: https://gist.github.com/thiagola922/fcd80f0f29b83106304c3b64cf64b2b1
As #marquis-of-lorne said, a better way to check if the connection still open is using resultSet.next().

Copying Resultset content to arraylist and comparing both the values

In the below code I am copying resultset content to arraylist. First part of the wile loop i.e while(RS.next()) is returing the results but when cursor moves to
Next while loop i.e while(SR.next()) I am getting "result set is closed". Please help me where I am doing mistake.
String SSQ = "select DISTINCT S_NUMBER from OTG.S_R_VAL" +
" WHERE R_TS = (SELECT MAX(R_TS) FROM OTG.S_R_VAL) order by S_NUMBER";
String SDS = "SELECT DISTINCT S_NUMBER FROM OTG.S_R_VAL AS STG WHERE S_NUMBER NOT IN" +
"(SELECT S_NO FROM OTG.R_VAL AS REV WHERE STG.S_NUMBER = REV.S_NO )";
String SSR = "SELECT DISTINCT S_NO FROM OTG.R_VAL where S_NO != 'NULL' order by S_NO";
String SSO = "Select O_UID from OTG.OPTY where C_S_NO IN" +
"( SELECT DISTINCT S_NUMBER FROM OTG.S_R_VAL AS STG WHERE S_NUMBER NOT IN(SELECT S_NO FROM OTG.R_VAL AS REV WHERE STG.S_NUMBER = REV.S_NO ))";
//Statement statement;
try {
connection = DatabaseConnection.getCon();
statement = connection.createStatement();
statement1 = connection.createStatement();
statement2 = connection.createStatement();
statement3 = connection.createStatement();
statement4 = connection.createStatement();
ResultSet RS = statement1.executeQuery(selectQuery);
ResultSet DS = statement2.executeQuery(Distinct_SiebelNo);
ResultSet SR = statement3.executeQuery(SiebelNo_Rev);
ResultSet SO = statement4.executeQuery(selected_OppId);
ArrayList<String> RSList = new ArrayList<String>();
ArrayList<String> SRList = new ArrayList<String>();
/* ResultSetMetaData resultSetMetaData = RS.getMetaData();
int count = resultSetMetaData.getColumnCount();*/
int count=1;
System.out.println("******count********"+count);
while(RS.next()) {
int i = 1;
count=1;
while(i < count)
{
RSList.add(RS.getString(i++));
}
System.out.println(RS.getString("SIEBEL_NUMBER"));
RSList.add( RS.getString("SIEBEL_NUMBER"));
}
/* ResultSetMetaData resultSetMetaData1 = SR.getMetaData();
int count1 = resultSetMetaData1.getColumnCount();*/
int count1=1;
while(SR.next()) {
int i = 1;
while(i < count1)
{
SRList.add(SR.getString(i++));
}
System.out.println(SR.getString("SIEBEL_NO"));
SRList.add( SR.getString("SIEBEL_NO"));
}SR.close();
connection.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
The logic of each loop is flawed.
int count=1;//Count is being set to one
while(RS.next()) {
int i = 1;//i is being set to one
count=1;//count again set to one
while(i < count) //condition will always fail as one is never less than one
{
RSList.add(RS.getString(i++));//Code is never Reached
}
System.out.println(RS.getString("SIEBEL_NUMBER"));
RSList.add( RS.getString("SIEBEL_NUMBER"));
}
The second while is not needed. Just use this:
int count = 1;
while(RS.next()) {
RSList.add(RS.getString(count++));
System.out.println(RS.getString("SIEBEL_NUMBER"));
RSList.add( RS.getString("SIEBEL_NUMBER"));
}
EDIT
int count1=1;
while(SR.next()) {
SRList.add(SR.getString(count1++));
System.out.println(SR.getString("SIEBEL_NO"));
SRList.add( SR.getString("SIEBEL_NO"));
}
EDIT 2:
for (String s : RSList)
for(String s1 : SRList)
if (s.equals(s1))
//Do what you need
You are using the first resultset (RS) in the second loop (System.out.println line)

Categories