Storing array and accessing them - java

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();

Related

execute query according to condition

PreparedStatement pstmt = null;
ResultSet rs = null;
List<SelectItemsDTO> listItem = new ArrayList<SelectItemsDTO>();
try {
StringBuilder query =new StringBuilder();
query = query.append(SLCMQueryConstant.GET_CollegeChid_LIST);
pstmt = conn.prepareStatement(query.toString());
pstmt.setInt(1,commonDto.getOrgID());
rs = pstmt.executeQuery();
int pid= 0;
while (rs.next()) {
pid= rs.getInt("organization_parent_id");
}
if(pid!= 0)
{
query = query.append(SLCMQueryConstant.GET_CollegeSub_LIST.toString());
pstmt = conn.prepareStatement(query.toString());
}
else
{
query = query.append(SLCMQueryConstant.GET_College_LIST.toString());
pstmt = conn.prepareStatement(query.toString());
}
pstmt.setInt(1,commonDto.getOrgID());
rs = pstmt.executeQuery();
while (rs.next()) {
SelectItemsDTO itemTo = new SelectItemsDTO();
itemTo.setItemCode(rs.getString("Organization_Name"));
itemTo.setItemIds(rs.getInt("Organization_ID"));
listItem.add(itemTo);
}
}
public static final String GET_College_LIST= " SELECT Organization_Name,Organization_ID FROM m_organization_master WHERE organization_parent_id = ? ";
public static final String GET_CollegeSub_LIST = " SELECT Organization_Name,Organization_ID FROM m_organization_master WHERE Organization_ID = ? ";
I want to execute query according to if condition .I am getting PID value from database and then used as if condition .This code seems an error no value specified for parameter 1 I have already initialized parameter for passing the values.

Display multiple query results java

Ok, so I'm having some difficulties in returning multiple results on this query in Java
public String getActive() throws SQLException
{
Connection con = DBConnect.getConnection();
String numeUser = "";
String sql=("select NUME from agents WHERE ACTIV = ? AND FILIALA = ? ");
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setInt(1, 1);
pstmt.setString(2, "MS10");
ResultSet rs = pstmt.executeQuery();
while(rs.next())
{
numeUser = rs.getString("NUME");
}
rs.close();
con.close();
return numeUser;
}
I heard something about that i can return the result with split() method or tokenizer but I don't seem to return the right result.
Agenti q2 = new Agenti();
String str1 = q2.getActive();
StringTokenizer stk1 = new StringTokenizer(str1);
String[] s1 = new String[0];
int i = 0;
while(stk1.hasMoreElements())
{
s1[i] = (String) stk1.nextElement();
i++;
}
System.out.println(s1[0]);
This is my tokenizer code. Can someone help me a little, please?

how to get multiple values from one text field with delimiter and save each to database

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());
}
}

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)

ResultSet to Integer array in Java

How can I convert a ResultSet to an Integer array?
I really need an Integer array. No Lists or something like that.
ResultSet rs = sqlite.query("SELECT ores FROM testtable WHERE nicknames='"+"testname"+"';");
"ores" contains 8 integers separated by a space: 10 20 30 40 50 60 70 80
Edit:
"ores" is stored as VARCHAR
Bad code. I'd recommend a PreparedStatement:
PreparedStatement ps = connection.prepareStatement("SELECT ores FROM testtable WHERE nicknames= ?");
ps.setString(1, nickname);
ResultSet rs = ps.executeQuery();
List<Integer> values = new ArrayList<Integer>();
while (rs.next()) {
String ores = rs.getString("ores");
String [] tokens = ores.split("\\s+");
for (int i = 0; i < tokens.length; ++i) {
values.add(Integer.valueOf(tokens[i]));
}
}
The ResultSet is the result of yourr query, if you want to transform it to an ArrayList or a simple Integer array, you can iterate over the ResulstSet and add all the non-null Object to your ArrayList or array. This is a simple solution...
Vector<Integer> ores = new Vector<Integer>();
rs.beforeFirst();
while(rs.next()){ores.add(rs.getInt(1));}
Integer[] vals = ores.toArray(new Integer[0]);
Maybe something like:
rs.last();
rowcnt = myResultSet.getRow(); // get row no.
rs.beforeFirst();
int i = 0;
Integer[] options = new Integer[rowcnt];
while (rs.next()) {
options[i] = Integer.parseInt(rs.getString(i));
i++;
}

Categories