How to get query resultset into a string - java

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+="|";
}

Related

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?

Only display highest value

I want this function to display the highest value and the index in the array.If the index is the highest, it will retrieve all the value in sql. But when I run this program, it displays a lot of values...How to solve it?
private void pick_highest_value_here_and_display(ArrayList<Double> value) throws Exception {
// TODO Auto-generated method stub
double aa[]=value.stream().mapToDouble(v -> v.doubleValue()).toArray();
double highest=aa[0];
System.out.println(highest); // display value in aa[0]
for(int i=1;i<aa.length;i++)
{
if(aa[i]>highest)
{
highest=aa[i];
System.out.println(highest); //print the highest value only
System.out.println(i);
String sql ="Select * from placeseen where ID =?";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDouble(1, i+1);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
String aaa=rs.getString("place1");
String bbb=rs.getString("place2");
String cc=rs.getString("place3");
String dd=rs.getString("place4");
String ee=rs.getString("place5");
String ff=rs.getString("place6");
String gg=rs.getString("place7");
String hh=rs.getString("place8");
String iii=rs.getString("place9");
String jj=rs.getString("place10");
String kk=rs.getString("place11");
String ll=rs.getString("place12");
String mm=rs.getString("place13");
String nn=rs.getString("place14");
String oo=rs.getString("place15");
String pp=rs.getString("budget");
Tourism to =new Tourism();
to.setPlace1(aaa);
to.setPlace2(bbb);
to.setPlace3(cc);
to.setPlace4(dd);
to.setPlace5(ee);
to.setPlace6(ff);
to.setPlace7(gg);
to.setPlace8(hh);
to.setPlace9(iii);
to.setPlace10(jj);
to.setPlace11(kk);
to.setPlace12(ll);
to.setPlace13(mm);
to.setPlace14(nn);
to.setPlace15(oo);
to.setBudget(pp);
DispDay dc=new DispDay();
dc.setVisible(true);
}
ps.close();
rs.close();
conn.close();
}
else if(highest==aa[0])
{
String sql ="Select * from placeseen where ID =1";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
String aaa=rs.getString("place1");
String bbb=rs.getString("place2");
String cc=rs.getString("place3");
String dd=rs.getString("place4");
String ee=rs.getString("place5");
String ff=rs.getString("place6");
String gg=rs.getString("place7");
String hh=rs.getString("place8");
String iii=rs.getString("place9");
String jj=rs.getString("place10");
String kk=rs.getString("place11");
String ll=rs.getString("place12");
String mm=rs.getString("place13");
String nn=rs.getString("place14");
String oo=rs.getString("place15");
String pp=rs.getString("budget");
Tourism to =new Tourism();
to.setPlace1(aaa);
to.setPlace2(bbb);
to.setPlace3(cc);
to.setPlace4(dd);
to.setPlace5(ee);
to.setPlace6(ff);
to.setPlace7(gg);
to.setPlace8(hh);
to.setPlace9(iii);
to.setPlace10(jj);
to.setPlace11(kk);
to.setPlace12(ll);
to.setPlace13(mm);
to.setPlace14(nn);
to.setPlace15(oo);
to.setBudget(pp);
DispDay dc=new DispDay();
dc.setVisible(true);
}
ps.close();
rs.close();
conn.close();
}
}
Use MAX
Please change your approach, and use the SQL MAX function. Something like,
String sql = "SELECT * FROM placeseen WHERE budget = ("
+ "SELECT MAX(budget) FROM placeseen)";
You could then use something like
int id = rs.getInt("id");
float budget = rs.getFloat("budget");
And I would recommend limiting the columns (if you only want the two) like
String sql = "SELECT id, budget FROM placeseen WHERE budget = ("
+ "SELECT MAX(budget) FROM placeseen)";
Why not use a for (int i = 0; i < array.lenght; i++)?
Store array[i] in a variable, and the actual int found in that index in another variable. Then, when you loop through it more: if (array[i] > biggestInt), store the new index number and new biggest integer in their appropriate variables.

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

Getting NullPointerException in Java SQLite

I code this method to fetch result from SQLite table in java.
public String[][] select(String query, String table) throws ClassNotFoundException, SQLException
{
Connection con;
Statement st;
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:"+table);
con.setAutoCommit(false);
st = con.createStatement();
ResultSet rs = st.executeQuery(query);
String[][] result = new String[100][4];
int j = 0;
while ( rs.next() ) {
String name = rs.getString("fullname");
String username = rs.getString("username");
String password = rs.getString("password");
String email = rs.getString("email");
result[j][0] = name; // line number 63
result[j][1] = username;
result[j][2] = password;
result[j][3] = email;
j++;
}
rs.close();
st.close();
con.close();
return result;
}
From my main method i instantiated this method:
try{
String[][] data = db.select("SELECT * FROM user", "fliplist.db"); // line number 37
System.out.println(data);
} catch (ClassNotFoundException | SQLException e){
System.out.println(e.getMessage());
}
This gives me this error:
run:
Exception in thread "main" java.lang.NullPointerException
at FlipList.Database.select(Database.java:63)
at FlipList.FlipList.main(FlipList.java:37)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
How it should be in order to fetch the result?
Update
I have initialized the second dimension of the array, and now it showing this error(most likely garbez value):
run:
[[Ljava.lang.String;#2077d4de
BUILD SUCCESSFUL (total time: 2 seconds)
How i can return an array?
(Thanks to #lea for this; if they've posted one please let me know)
You need to initialize the inner arrays, too. In your while loop, put something like this at the top, and it should work.
data[j] = new String[4];
For your new error, you want to iterate through the array instead of just printing it. For example:
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[0].length; j++) {
System.out.print(data[i][j] + "\t\t");
}
System.out.println();
}
There are also a couple of other tips that I'd like to give you:
Move the j++ into the while loop, just before the closing bracket. That way it increments with every loop instead of just once, after every loop. Fixed!
You might want to use an ArrayList<String[]> instead of String[][] if you won't always have exactly a hundred items. That way, you can go over 100 if you need, and if you use less, it will save memory. To do that, you'll want to do something like this for your while loop:
while ( rs.next() ) {
String[] nextRow = new String[4];
String name = rs.getString("fullname");
String username = rs.getString("username");
String password = rs.getString("password");
String email = rs.getString("email");
nextRow[0] = name; // line number 63
nextRow[1] = username;
nextRow[2] = password;
nextRow[3] = email;
result.add(nextRow);
}
You'll also want to change the declaration of data to ArrayList<String[]> result = new ArrayList<String[]>() instead of String[][] result = ....
i redefined the ArrayList as the list of Strings rather than Arrays.
public void tester()
{
ArrayList result = new ArrayList();
try
{
Connection connect = DriverManager.getConnection(host, username, password);
String sql="select * from FRIENDS";
Statement stmt=connect.createStatement();
ResultSet rs=stmt.executeQuery(sql);
String[] nextRow = new String[4];
while ( rs.next() ) {
String firstname = rs.getString("FIRSTNAME");
String lastusername = rs.getString("LASTNAME");
String nickname = rs.getString("NICKNAME");
String friendsince = rs.getString("FRIENDSINCE");
String email = rs.getString("EMAIL");
System.out.print("Firstname :- "+firstname+" lastname :- "+lastusername+" nickname :- "+nickname+" friendsince :- "+friendsince+" Email :- "+email);
nextRow[0] = firstname;
nextRow[1] = lastusername;
nextRow[2] = nickname;
nextRow[3] = email;
System.out.println("The values in array are :- "+nextRow);
int i=0;
for(i=0;i<nextRow.length;i++)
{
String add1=nextRow[i];
result.add(add1);
}
}
}
Hope , this helps.
Something very basic . Please execute the query on the DB and see what it returns(Sometimes the query might not be correct e.g the table name can be 'users' instead of 'user', just a guess) :-
SELECT * FROM user
If above is fine , then can you please try extracting the rows using 'columnIndex' instead of the 'columnName'. e.g.
String name = rs.getString(1);
String username = rs.getString(2);
String password = rs.getString(3);
String email = rs.getString(4);
Here i am assuming that the name , username , password and email belong to 1st , 2nd ,3rd and 4th column respectively.

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