ResultSet to Integer array in Java - 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++;
}

Related

Retrieving data from a table based on values in a hashmap

I have an hashmap with a key and value (Array of integers) HashMap<key, array> and I would like to retrieve data from a sql table with a column that matches the values in array stored in a hashmap
I can do this in two ways one getting all the data from table and iterating through hashmap and other being iterating through hashmap and applying the where clause in each iteration which makes n calls to database.
Is there an efficient way to do this other than the above ?
Use a PreparedStatement to set up a query having an IN condition in the WHERE clause. This snippet should give you the general idea:
values = new int[]{1,2,3,4,5};
String query =
"SELECT film_id, title\n"
+ "FROM film\n"
+ "WHERE film_Id IN (";
for (int i = 0; i < values.length; ++i) {
if (i > 0) {
query += ",";
}
query += "?";
}
query += ")";
try {
Connection conn = DriverManager.getConnection("db-url", "user", "pwd");
PreparedStatement stmt = conn.prepareStatement(query);
for (int i = 0; i < values.length; ++i)
stmt.setInt(i+1, values[i]);
ResultSet rs = stmt.executeQuery();
while (rs.next()){
// process results
}
} catch (Exception ex) {
ex.printStackTrace();
}

Iterating metadata.getColumnCount()

Basically I am trying to read multiple queries from excel sheet through jexel and I am adding the cell contents to Key and Value in hashmap. For example
A1=1 (Key) , A2 =2 ....
B1 = "SELECT * FROM ABCD;" (Value), B2 = "SELECT * FROM XYZ;"
Map<String, String> hashmap = new HashMap<String, String>();
for (int i=0;i<rowCount;i++) {
Cell rowObj1 =sheet.getCell(0, i);
Cell rowObj2 = sheet.getCell(1, i);
sql =rowObj2.getContents();
hashmap.put(rowObj1.getContents(), rowObj2.getContents());
}
Later I am getting the SQL(s) from the hashmap by iterating over rowCount on exel sheet.
Then I am adding all SQL(s) result sets to an array list
and finally I am iterating over array list size to get individual record set, at the same time get metadata for the record set.
However the problem here is I get
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.ArrayList.elementData(ArrayList.java:418)
at java.util.ArrayList.get(ArrayList.java:431)
at com.bmc.arsys.jdbc.core.ResultSetMetaData.getColumnCount(ResultSetMetaData.java:47)
on
int ColCount = metadata1.getColumnCount();
and here is the code snippet
ArrayList<ResultSet> arraylist = new ArrayList<ResultSet>();
int i;
String y;
for (i=1;i<=rowCount;i++){
y = Integer.toString(i);
sql =hashmap.get(y);
rs = st.executeQuery(sql);
arraylist.add(rs);
System.out.println(sql);
}
System.out.println("Array List Size "+arraylist.size());
for (int j=0;j<arraylist.size();j++){
ResultSet rs1= arraylist.get(j);
System.out.println("Record Set "+rs1);
ResultSetMetaData metadata1 = rs1.getMetaData();
System.out.println("Meta Data "+metadata1);
int ColCount = metadata1.getColumnCount();
System.out.println(ColCount);
int k;
for (k=1;k<ColCount;k++) {
System.out.println("Record_Set "+rs1);
while(rs1.next()) {
System.out.println(rs1.getString(k));
}
}
}
could someone please suggest where I am wrong.

Storing array and accessing them

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

converting resultset to multidimensional string array

I am trying to convert ResultSet to String[][] in Java webservice. It sounds very stupid to convert the Resultset to Strin[][]. The reason I am trying to do this is because Java webservice is called from .Net and it doesnt understand the ResultSet. I hoped it would had accepted the ResultSet as a DataTable but it didnt work out.
One of my problems is that the server I am trying to test my Java webservice is terrible and I cannot work very efficiently, so I cannot test everything.
this is my java webservice. I am trying to convert it to String[][] but it returns null. I think I am doing something wrong when I try to fill the String[][].
Is it correct way to get the rowCount and columnCount of ResultSet? what am I doing wrong?
public String[][] getValues()
{
String[][] arr;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/MLS_J", "sa", "12345");
java.sql.Statement stmt = conn.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
java.sql.ResultSet rslt = stmt.executeQuery("SELECT * FROM S_USERS");
// to get row count and column count
/////////////////////////////////////
int rowSize = 0;
try {
rslt.last();
rowSize = rslt.getRow();
rslt.beforeFirst();
}
catch(Exception ex) {
}
ResultSetMetaData rsmd = rslt.getMetaData();
int columnSize = rsmd.getColumnCount();
/////////////////////////////////////
arr = new String[rowSize][columnSize];
int i =0;
while(rslt.next() && i < rowSize)
{
for(int j=0;j<columnSize;j++){
arr[i][j] = rslt.getString(j);
}
i++;
}
rslt.close();
stmt.close();
conn.close();
return arr;
} catch (Exception e) {
return null;
}
}
it is your problem
java resultset starts from 1.. so change your getString method like this. And remain all codes fine.
while(rslt.next() && i < rowSize)
{
for(int j=0;j<columnSize;j++){
arr[i][j] = rslt.getString(j+1);
}
i++;
}
A simple way to get the row count is to use COUNT(*) for your case...
java.sql.ResultSet rslt = stmt.executeQuery("SELECT COUNT(*) FROM S_USERS");

How to get query resultset into a string

In Java, after executing a query say I got a result set like:
bat 20 10
fat 20 5
cat 10 25
I want this resultset in a string such that the string will be:
bat,20,10 |fat,20,5 |cat,10,25
I am confused. How can I do that in Java?
ResultSet rs = ...
StringBuilder b = new StringBuilder();
while(rs.next()) {
String s = rs.getString(1);
int n1 = rs.getInt(2);
int n2 = rs.getInt(3);
b.append(s);
b.append(",");
b.append(n1);
b.append(",");
b.append(n2);
b.append("|");
}
while iterating through the resultset you can append its contents to a string ..right.?
String finalStr = "";
while(resultSet.next()){
finalStr+=resultSet.getString(1)+",";
finalStr+=resultSet.getInt(2).toString()+",";
finalStr+=resultSet.getInt(3).toString();
finalStr+="|";
}

Categories