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)
Related
I'am trying to update table from multiple columns names(lo1,lo2,...) that are to be taken dynamically. But the values are not getting updated in database.
column names are co1,co2....
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Connection conn = null;
PreparedStatement pstmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/netbeans","root","");
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM colo");
rs = st.executeQuery("SELECT COUNT(*) FROM colo");
// get the number of rows from the result set
rs.next();
int rowCount = rs.getInt(1);
//txt_ans.setText(String.valueOf(rowCount));
int num_1 =300;
int num_2 =200;
int num_3 =300;
int num_4 =400;
String value = null;
int value1 ;
for(int i=1;i<=rowCount;i++)
{
String sql =("SELECT * FROM colo WHERE id = '"+i+"'");
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery(sql);
while(rs.next())
value = rs.getString("co1");
//txt_ans.setText(String.valueOf(value));
String x = "co2";
if(value.equals("lo1"))
{
// value1= 1;
// txt_ans.setText(String.valueOf(value1));
String sql1 =("update colo set '"+x+"' = '"+num_1+"' where id = '"+i+"'");
pstmt = conn.prepareStatement(sql1);
int r = pstmt.executeUpdate(sql1);
txt_ans.setText(String.valueOf(r));
}
else if(value.equals("lo2"))
{
// value1= 1;
// txt_ans.setText(String.valueOf(value1));
String sql1 =("update colo set '"+ x +"' = '"+num_2+"' where id = '"+i+"'");
pstmt = conn.prepareStatement(sql1);
int r = pstmt.executeUpdate(sql1);
txt_ans.setText(String.valueOf(r));
}
else
{
value1 = 9009;
txt_ans.setText(String.valueOf(value1));
}
}
The problem is with using single quotes for column name i.e, like 'x', so just remove them as shown below:
String sql1 =("update colo set " + x + " = ? where id = ?");//no single quote for x
pstmt = conn.prepareStatement(sql1);
pstmt.setString(1, num_1);
pstmt.setString(2, i);
int r = pstmt.executeUpdate(sql1);
Also, always use prepareStatement's setString, etc.. methods for setting the values which is recommended.
Apply the same concept for the other query inside the else if(value.equals("lo2")) block as well.
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.
This is the coding which I have used to retrieve data from the "GeneID" column. Using this coding I can print all names under the "GeneID" column. But I want to store each and every names from the column to access those name separately. Can anyone help me with this?
String name1[] = new String[100];
int i = 0;
String query = "select distinct GeneID from gene1";
PreparedStatement pest = connection.prepareStatement(query);
ResultSet rs = pest.executeQuery();
while (rs.next()) {
name1[i] = rs.getString("GeneID");
System.out.println(name1[i]);
}
rs.close();
pest.close();
For using array you have to increment i inside the while (rs.next()) {
String name1[] = new String[100];
int i = 0;
String query = "select distinct GeneID from gene1";
PreparedStatement pest = connection.prepareStatement(query);
ResultSet rs = pest.executeQuery();
while (rs.next()) {
name1[i] = rs.getString("GeneID");
System.out.println(name1[i]);
i++;
}
rs.close();
pest.close();
}
For accessing you can iterate over the array
for(int i;i<name1.length-1;i++){
System.out.println("Id is "+name1[i]);
}
Or you can use
for (String id: name1) {
System.out.println("Id is "+name1[i]);
}
You can also use ArrayList to store variable like below
ArrayList ar=new ArrayList();
String query = "select distinct GeneID from gene1";
PreparedStatement pest = connection.prepareStatement(query);
ResultSet rs = pest.executeQuery();
while (rs.next()) {
String id = rs.getString("GeneID");
ar.add(id);
}
rs.close();
pest.close();
}
For iterating over ArrayList
for (int i = 0; i < ar.size(); i++) {
System.out.println("Id is "+ar.get(i));
}
or
for (String id : ar) {
System.out.println("Id is "+ar.get(i));
}
use arrayList, so that you can use a method of .add(), this proves much helpful
List ls=new ArrayList();
ResultSet rsp=pss.executeQuery("select * from student");
while(rsp.next()){
ls.add(rsp.getString("your_column_name"));
}
rsp.close();
actually I have 10-30 dummies to get the value from txtCC, but i'd only used 3 dummies for example below..
So how do I get each values and save it directly to my database without using dummy? It's a big deal coz' my code was too large to compile using those dummies..
THANKS for any help..
private void bSaveActionPerformed(java.awt.event.ActionEvent evt)
{
// Save to database
String cc = txtCC.getText();
String delimiter = ",";
String[] temp;
temp = cc.split(delimiter);
for(int i = 0; i < temp.length; i++)
if(i==0) {
txtC1.setText(temp[0]);
txtC2.setText("0");
txtC3.setText("0"); }
else if (i==1) {
txtC1.setText(temp[0]);
txtC2.setText(temp[1]);
txtC3.setText("0"); }
else if (i==2) {
txtC1.setText(temp[0]);
txtC2.setText(temp[1]);
txtC3.setText(temp[2]); }
try {
String cc1 = txtC1.getText(); int CC1 = Integer.parseInt(cc1);
String cc2 = txtC2.getText(); int CC2 = Integer.parseInt(cc2);
String cc3 = txtC3.getText(); int CC3 = Integer.parseInt(cc3);
int opt = JOptionPane.showConfirmDialog(null,"Are you sure you want to save this record? ");
if (opt == 0){
if(!txtC1.getText().equals("0")) {
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "Select * from tbl_liqinfo";
rs = stmt.executeQuery(sql);
rs.next();
rs.moveToInsertRow();
rs.updateInt("CC", CC1);
rs.insertRow();
rs.close();
}
if(!txtC2.getText().equals("0")) {
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "Select * from tbl_liqinfo";
rs = stmt.executeQuery(sql);
rs.next();
rs.moveToInsertRow();
rs.updateInt("CC", CC2);
rs.insertRow();
rs.close();
}
if(!txtC3.getText().equals("0")) {
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "Select * from tbl_liqinfo";
rs = stmt.executeQuery(sql);
rs.next();
rs.moveToInsertRow();
rs.updateInt("CC", CC3);
rs.insertRow();
rs.close();
}
}
}
catch (SQLException err){
JOptionPane.showMessageDialog(FrmEmpLiquidation.this, err.getMessage());
}
}
Instead of using dummies, create simple small methods and make use of it. This will reduce you line of code. and also easy to understand.
private void bSaveActionPerformed(java.awt.event.ActionEvent evt){
// Save to database
String cc = txtCC.getText();
String delimiter = ",";
String[] temp;
temp = cc.split(delimiter);
for(int i = 0; i < temp.length; i++)
insertData(temp[i]);
}
public void insertData(final String data){
txtC1.setText(data);
try {
String cc1 = txtC1.getText(); int CC1 = Integer.parseInt(cc1);
int opt = JOptionPane.showConfirmDialog(null,"Are you sure you want to save this record? ");
if (opt == 0){
if(!txtC1.getText().equals("0")) {
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "Select * from tbl_liqinfo";
rs = stmt.executeQuery(sql);
rs.next();
rs.moveToInsertRow();
rs.updateInt("CC", CC1);
rs.insertRow();
rs.close();
}
}
}
catch (SQLException err){
JOptionPane.showMessageDialog(FrmEmpLiquidation.this, err.getMessage());
}
}
I'm new to java.I have a SQL Query that gives the following output
logtime 2014-09-02 16:05:10.0
BL1_data_SS_ST 2
BL2_data_SS_ST 2
BL3_data_SS_ST 2
BL4_data_SS_ST 1
BL5_data_SS_ST 0
BL6_data_SS_ST 2
/* continues till BL27_data_SS_ST */
st1_prmt_status_p45 1
beam_current 110.58
beam_energy 2500.0635
I have only one row in my output and 31 columns. I'm using Java and JSP .
EDIT
The above result is retrieved by the following method
public String[][] beamline_Status() {
int i = 0;
try {
con = getConnection();
stmt = con.createStatement();
String sql = "SELECT TOP 1 c.logtime, a.BL1_data_SS_ST,a.BL2_data_SS_ST,a.BL3_data_SS_ST,a.BL4_data_SS_ST,a.BL5_data_SS_ST,a.BL6_data_SS_ST,a.BL7_data_SS_ST,a.BL8_data_SS_ST,a.BL9_data_SS_ST,a.BL10_data_SS_ST,a.BL11_data_SS_ST, a.BL12_data_SS_ST,a.BL13_data_SS_ST,a.BL14_data_SS_ST,a.BL15_data_SS_ST,a.BL16_data_SS_ST,a.BL17_data_SS_ST,a.BL18_data_SS_ST,a.BL19_data_SS_ST,a.BL20_data_SS_ST,a.BL21_data_SS_ST,a.BL22_data_SS_ST,a.BL23_data_SS_ST,a.BL24_data_SS_ST,a.BL25_data_SS_ST,a.BL26_data_SS_ST,a.BL27_data_SS_ST,b.st1_prmt_status_p45,c.beam_current,c.beam_energy from INDUS2_BLFE.dbo.main_BLFE_status a inner join INDUS2_MSIS.dbo.main_MSIS_status b on a.logtime=b.logtime inner join INDUS2_BDS.dbo.DCCT c on b.logtime=c.logtime ORDER BY c.logtime DESC ";
stmt.executeQuery(sql);
rs = stmt.getResultSet();
while (rs.next()) {
for (int j = 0; j < 31; j++) {
a[i][j] = rs.getString(j + 1);
}
}
} catch (Exception e) {
System.out.println("\nException (String code):" + e);
} finally {
closeConnection(stmt, rs, con);
}
return a;
}
Now I wan to define a method which retrieve values from the ResultSet where column values are either 0 or 1. How to do that.
EDIT 2
I'm trying to retrieve the column values from resultset where column value is 1 by following code:-
public String[][] beam_CurrentStatus() {
int i = 0;
try
{
con = getConnection();
stmt = con.createStatement();
String sql = "SELECT TOP 1 c.logtime, a.BL1_data_SS_ST,a.BL2_data_SS_ST,a.BL3_data_SS_ST,a.BL4_data_SS_ST,a.BL5_data_SS_ST,a.BL6_data_SS_ST,a.BL7_data_SS_ST,a.BL8_data_SS_ST,a.BL9_data_SS_ST,a.BL10_data_SS_ST,a.BL11_data_SS_ST, a.BL12_data_SS_ST,a.BL13_data_SS_ST,a.BL14_data_SS_ST,a.BL15_data_SS_ST,a.BL16_data_SS_ST,a.BL17_data_SS_ST,a.BL18_data_SS_ST,a.BL19_data_SS_ST,a.BL20_data_SS_ST,a.BL21_data_SS_ST,a.BL22_data_SS_ST,a.BL23_data_SS_ST,a.BL24_data_SS_ST,a.BL25_data_SS_ST,a.BL26_data_SS_ST,a.BL27_data_SS_ST,b.st1_prmt_status_p45,c.beam_current,c.beam_energy from INDUS2_BLFE.dbo.main_BLFE_status a inner join INDUS2_MSIS.dbo.main_MSIS_status b on a.logtime=b.logtime inner join INDUS2_BDS.dbo.DCCT c on b.logtime=c.logtime ORDER BY c.logtime DESC ";
stmt.executeQuery(sql);
rs = stmt.getResultSet();
while (rs.next()) {
for (int j = 1; j < 31; j++) {
if ((rs.getString(j)) == "1")
a[i][j] = rs.getString(j + 1);
}
}
} catch (Exception e) {
System.out.println("\nException in:" + e);
} finally {
closeConnection(stmt, rs, con);
}
return a;
}
But the result I'm getting of above code is
[[Ljava.lang.String;#ea25c1
If you want entire table in the ResultSet and then obtain only the first and second column out of it you can do like:
Statement stmt=conn.createStatement();
ResultSet rs= stmt.executeQuery("select * from tableName");
rs.getInt(1); //assuming your column is of compatible type
rs.getInt(2);
or the other way is that you retrieve only the first two columns from the DB into your ResultSet