ResultSet Data of every row store in other array index - java

I am new in JAVA, so kindly understand my question and please give your valuable and precise answer.
How to store resultset data in anohter array ? Should I use ArrayList etc. My code is just for example.
Statement stmt = null;
ResultSet query_rs;
String query = "SELECT * FROM my_table";
query_rs = stmt.executeQuery(query);
int counter_rs = 0;
ArrayList my_arr = new ArrayList();
while(query_rs.next())
{
//here I want to add one row data in array index
counter_rs++;
my_arr[counter_rs] = query_rs; //Store row data in particular array index
}
System.out.println(my_arr.toString()); //Show all data
P.S. My major line is my_arr[counter_rs] = query_rs;. Thanks in advance

my_arr is arraylist if you want to add any element my_arr.add(anyElement) or if you want to set any element in particular location use this set(int index, E element)
my_arr.set(0,anyElement);
Statement stmt = null;
ResultSet query_rs;
String query = "SELECT * FROM my_table";
query_rs = stmt.executeQuery(query);
int counter_rs = 0;
ArrayList my_arr = new ArrayList();
while(query_rs.next())
{
//here I want to add one row data in array index
my_arr.set(counter_rs,query_rs); //use this
// or
// my_arr.add(query_rs);
counter_rs++;
}
//System.out.println(my_arr.toString()); //Show all data
// use for loop to get all data

my_arr is ArrayList not array
ArrayList my_arr = new ArrayList();
use my_arr.add() not as my_arr[counter_rs] = query_rs;

If i understand your question, then i think you need to do the following:
First declare an arrayList with a RowType like >
ArrayList<DataRow> my_arr = new ArrayList<DataRow>(); // DataRow should hold the columns data.
Second : add each fetched row to the list.
while(query_rs.next())
{
DataRow row = // fill the row from the ResultSet
my_arr.add(row);
}
third : loop over the list and print the data;

Related

Retrieve specific row from access table

I've looked through this forum and searched the web for a solution to my above problem but could not find something that points me in the right direction. Please forgive me if this is a duplication.
I'm working on a java project where my application interacts with an MS Access 2016 database. One of the functions of my program is to query the db for a specific record and display the data of that record in a gui. Here is my code to retrieve the data:
int i = 0;
String q = "select * from QueryData where id=123456";
try {
pstmnt=conn.prepareStatement(q);
Object obj ;
rs = pstmnt.executeQuery();
while (rs.next()) {
obj=rs.getObject(i+1);
data.add(obj); //where data is a List object i++;
}
} catch ....
Problem is I only get the first value in this record (1st column of record) and there are more data available in the record/row.
Could it be the rs.next() method that is doing this and if so, what should I use to get the next value in this specific record?
ResultSet#next() iterates over the rows in the result set (which, in this case, is just a single row). If you don't know the result set's structure upfront, you can dynamically deduce it from a ResultSetMetaData object:
int i=0;
String q="select * from QueryData where id=123456";
try (PreparedStatement pstmnt = conn.prepareStatement(q);
ResultSet rs = pstmnt.executeQuery()) {
ResultSetMetaData rsmd = rs.getMetaData();
// Assume it's just one row.
// If there's more than one, you need a while loop
if (rs.next()) {
for (int i = 0; i < rsmd.getColumnCount(); ++i) {
data.add(rs.getObject(i + 1));
}
}
}

How to use next() inside the for loop in java for getting next resultset

I am want to take id of each no which are presented in the array constant. Please find the below code. When i am running this i am getting "ResultSet not positioned properly, perhaps you need to call next." error. but 101 working correctly. rest of the values or not fetched. Please anyone help me
PreparedStatement m_inoutid = null;
docno="[101,102,103,104]";
String minoutid[]=new String[1000];
String documentno = docno.substring(1, docno.length() - 1);
List<String> docnumbers = new ArrayList<String>();
String[] split = documentno.split(",");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < split.length; i++) {
String sql = "select id from mytable where fid=?";
outid = conn.prepareStatement(sql);
String idfromquery=split[i];
outid.setString(1, idfromquery);
ResultSet idResultSet = outid.executeQuery();
idResultSet.next();
id = idResultSet.getString("id");
final List<Object> parameters = new ArrayList<Object>();
parameters.add(null);
parameters.add(id);
myfunction(parameters);
}
I can see here two things that you might try:
You can check if all of your queries return at least one row. Maybe there is an ID you pass to the query that does not validate the WHERE clause for any of the results. You can check this by placing the call to next in a conditional statement like
if(idresultSet.next()) id = idResultSet.getString("id");
Additionally, maybe you should try to place the cursor to the first row (just to be sure) after executing the query. Like
ResultSet idResultSet = outid.executeQuery();
idResultSet.first();
idResultSet.next();

List of String Arrays overwriting itself

First ever question here, complete newbie so try to take it easy on me. I'm trying to figure out what's wrong here:
public List<String[]> idOnlyQuery(String searchTerm, Connection conn){
List<String[]> result = new ArrayList<String[]>();
String[] rowResult = new String[7];
Statement stmt = null;
try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT * FROM Jets WHERE CurrentID LIKE '" + searchTerm + "%'");
while(rs.next()){
String currentId= rs.getString("CurrentId");
String manufacturer = rs.getString("Constructor");
String type = rs.getString("ACType");
String series = rs.getString("Series");
String index = rs.getString("KeyNo");
String operator = rs.getString("Operator");
String baseAirport = rs.getString("Home_Airfield");
rowResult[0] = (currentId);
rowResult[1] = (manufacturer);
rowResult[2] = (type);
rowResult[3] = (series);
rowResult[4] = (operator);
rowResult[5] = (baseAirport);
rowResult[6]= (index);
result.add(rowResult);
}
System.out.println(result.get(0)[0]);
This method returns a list of string arrays, these arrays are retrieved from an SQLite database. Everything works apart from the fact that the string arrays in my result List seem to be getting overwritten every time the while loop repeats itself. The last println always gives me the currentId of the last row retrieved from the database, but if I put a println inside the while loop it returns the appropriate data on each while cycle. I really can't figure out where my String[] elements are getting overwritten. It's probably really obvious but I've spent hours looking online to check if I'm doing the add procedure correctly and still no joy. HELP!
You need to create the rowResult array in the loop. Your list just holds a pointer to the array and you are basically only working with one instance all the time.
in while use rowResult = new String[7]; everytime before initializing.
This is because, arrays are objects in Java, so basically you are changing value of same object again and again.
It's because you are reassigning the array locations:
rowResult[0] = (currentId);
rowResult[1] = (manufacturer);
rowResult[2] = (type);
rowResult[3] = (series);
rowResult[4] = (operator);
rowResult[5] = (baseAirport);
rowResult[6]= (index);
Create a temporary String array inside your while loop and add that to your result:
while (rs.next()) {
String[] rowResult = new String[7];
..
// do your stuff
result.add(rowResult);
}
Every time the while loop executes, it will add it to result and you will start anew.
You are using the same rowResult array for all rows. Put the line
String[] rowResult = new String[7];
inside the while loop, and everything will work fine.
You are overwriting your rowResult object. You have to create a new one, fill it and add it to your list every iteration. What you do is like taking a basket, fill it with oranges and put it on the shelve, then take the same basket, throw the oranges out and put new ones in.
public List<String[]> idOnlyQuery(String searchTerm, Connection conn){
List<String[]> result = new ArrayList<String[]>();
Statement stmt = null;
try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT * FROM Jets WHERE CurrentID LIKE '" + searchTerm + "%'");
while(rs.next()){
String[] rowResult = new String[7];
rowResult[0] = rs.getString("CurrentId");
rowResult[1] = rs.getString("Constructor");
rowResult[2] = rs.getString("ACType");
rowResult[3] = rs.getString("Series");
rowResult[4] = rs.getString("Operator");
rowResult[5] = rs.getString("Home_Airfield");
rowResult[6] = rs.getString("KeyNo");
result.add(rowResult);
}
System.out.println(result.get(0)[0]);
}
catch (Exception e) {}
}
You are overwritting again and again the String array. Try to create a new array in each loop.
List<String[]> result = new ArrayList<String[]>();
String[] rowResult;
Statement stmt = null;
try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT * FROM Jets WHERE CurrentID LIKE '" + searchTerm + "%'");
while(rs.next()){
rowResult = new String[7]; //Create a new object
String currentId= rs.getString("CurrentId");
//...
}
This is because when you are doing this:
rowResult = new String[7]; //Create a new object
This variable points out to an object in memory:
rowResult -------------> new String[7]
So if I do loop over and over the result set and write using rowResult I am indeed only modifying one object (by adding it every time to the list you only have a lot of variables pointing to the same object):
result.get(0) -------------->|
result.get(1)--------------->| String[7]
result.get(n)--------------->|
When creating by new operator an new array in the loop you are indeed having a new fresh object to work with:
result.get(0) -------------->| String[7]
result.get(1)--------------->| String[7]
result.get(n)--------------->| String[7]

MySQL: Out of range, but the column isn't last?

After an awful lot of time figuring out what's wrong with my code, I decided to go ahead and ask for help. As of right now this is the code which's causing the error:
try {
ResultSet rs = statement.executeQuery("SELECT `message` FROM `notifications` WHERE `active`='1'");
List<String> messages = new ArrayList<String>();
int index = 1;
if (rs.next()) {
while (!rs.isLast()) {
messages.add(rs.getString(index));
index ++;
}
if (rs.isLast()) {
messages.add(rs.getString(index));
}
}
return messages.toArray(new String[messages.size()]);
} catch (Exception localException) {
if (localException instanceof NullPointerException) {
/* ignore for now */
localException.printStackTrace();
} else {
localException.printStackTrace();
}
}
The error is telling me that the column is out of range, but when I look into my database it's not.
java.sql.SQLException: Column Index out of range, 2 > 1.
Any suggestions? Thanks in advance!
Inside the
if (rs.isLast()) {
messages.add(rs.getString(index));
}
The index will be 2, in this statement, but your resultSet only contains one column.
When you say rs.getString(2) it is going to grab the value associated with the 2nd column.
Should be :
ResultSet rs = statement.executeQuery("SELECT `message` FROM `notifications` WHERE `active`='1'");
List<String> messages = new ArrayList<String>();
int index = 1;
while (rs.next()) {
messages.add(rs.getString(index));
}
Note: A best practice is to get the value based on column name instead of index. I believe you thought that getString(index) accessed the row, and calling it by the column name would clear that up for you.
ResultSet rs = statement.executeQuery("SELECT `message` FROM `notifications` WHERE `active`='1'");
List<String> messages = new ArrayList<String>();
String column = "message";
while (rs.next()) {
messages.add(rs.getString(column));
}
The isLast method only determines if you're on the last row, not the last column. The way that you're using index is to iterate over all columns on the same row.
The way to determine the number of columns is to get the ResultSetMetaData object from the ResultSet and get the number of columns from it, using the getMetaData() method on the ResultSet and the getColumnCount() method on the ResultSetMetaData. Then you can use that to loop through your columns.
In your query you have just one column message in the SELECT clause. Remove index++ from your java code to get rid of the exception because rs.getString(index) is trying to get value of column number 2 which does not exists in the query result.

How to fetch entire row as array of objects with JDBC

I have to make a 'query' method for my class which accesses MySQL thru' JDBC.
The input parameter to the method is a full SQL command (with values included), so I don't know the names of columns to fetch out.
Some of the columns are strings, some others are integers, etc.
The method needs to return the value of type ArrayList<HashMap<String,Object>>
where each HashMap is 1 row, and the ArrayList contains all rows of result.
I'm thinking of using ResultSet.getMetaData().getColumnCount() to get the number of columns then fetch cell by cell out of the current row, but is this the only solution? any better ones?
I have the example code here, just in case anybody need it. ('Con' in the code is the standard JDBC connection).
//query a full sql command
public static ArrayList<HashMap<String,Object>>
rawQuery(String fullCommand) {
try {
//create statement
Statement stm = null;
stm = con.createStatement();
//query
ResultSet result = null;
boolean returningRows = stm.execute(fullCommand);
if (returningRows)
result = stm.getResultSet();
else
return new ArrayList<HashMap<String,Object>>();
//get metadata
ResultSetMetaData meta = null;
meta = result.getMetaData();
//get column names
int colCount = meta.getColumnCount();
ArrayList<String> cols = new ArrayList<String>();
for (int index=1; index<=Col_Count; index++)
cols.add(meta.getColumnName(index));
//fetch out rows
ArrayList<HashMap<String,Object>> rows =
new ArrayList<HashMap<String,Object>>();
while (result.next()) {
HashMap<String,Object> row = new HashMap<String,Object>();
for (String colName:cols) {
Object val = Result.getObject(colName);
row.put(colName,val);
}
rows.add(row);
}
//close statement
stm.close();
//pass back rows
return tows;
}
catch (Exception ex) {
System.out.print(ex.getMessage());
return new ArrayList<HashMap<String,Object>>();
}
}//raw_query

Categories