List of String Arrays overwriting itself - java

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]

Related

UCAExc:::3.0.7 unexpected token: logDate

Good day, all. I am working on a personal project that needs to interact with an ms access 2016 db. My java application gets data from a user and this info is stored in an Object[]. I am trying to insert the elements of my obj array to a table in my db. This is my code:
Connection conn = null;
PreparedStatement pstmnt = null;
String sql = null;
ResultSetMetaData md = null;
Statement stm = null;
ResultSet rs = null;
int i = 0;
String q = "SELECT * from QueryData";
try{
conn = DriverManager.getConnection("jdbc:ucanaccess://filePath");
stm = conn.createStatement();
rs = stm.executeQuery(q);
md = rs.getMetaData();
int count = md.getColumnCount();
String[] colName = new String[count];
for (int n = 1; n <= count; n++)
colName[n-1] = md.getColumnLabel(n);
while ( i <= data.length) {//data being the object array containing the data to be inserted in db
query = "INSERT into QueryData ('"+colName[i]+"') VALUES ('"+data[i]+"')";
//The following code is where I get the exception
pstmnt = conn.prepareStatement(query);
//some more code follows..
On the first pass throught the while loop, colName[i] is "logDate" which is the first field in the table and data[i] is a LocalDate object formatted as 2016-12-23. I know I did not close the while loop above nor did I given the catch clause, but my program does not run past the pstmnt assignment. I keep getting the exception "net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::3.0.7 unexpected token: logDate".
Any assistance will be greatly appreciated as I've scoured the web amd this forum but could not find a working solution to my problem.
You are surrounding your column name with quotes, which isn't allowed. You can use square brackets instead (although not really necessary unless you have spaces in the field names, which Access allows).
query = "INSERT into QueryData (["+colName[i]+"]) VALUES ('"+data[i]+"')";
You might also need to use # instead of ' to delimit the date value. Access used to use # for date delimiters, and I'm not sure if more recent versions accept ':
query = "INSERT into QueryData (["+colName[i]+"]) VALUES (#"+data[i]+"#)";

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

Reading data from MySQL into eclipse

I am trying to read data from my MySQL database into an array so that I can output the data in a view.
My code so far is :
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/database","localhost","root");
PreparedStatement stmt = con.prepareStatement("select * from stock");
ResultSet result = stmt.executeQuery("select * from stock");
ArrayList<int[]> stockNo = new ArrayList<int[]>();
ArrayList<String[]> stockName = new ArrayList<String[]>();
while(result.next()){
stockNo.add(result.getInt(1));
stockName.add(result.getString(2));
}
}
However I am getting an error message on the .add the method saying
"the method add(int,int[]) in the type ArrayList is not applicable for the arguements (int)".
Does anyone know how I can fix this? Is it because I havent defined the size of my arrays?
It's because you defined your List for storing arrays of ints, not ints.
Replace this:
ArrayList<int[]> stockNo = new ArrayList<int[]>();
By this:
ArrayList<Integer> stockNo = new ArrayList<Integer>();
result.getInt(1) and result.getString(2) return Integer and String respective. You can not add to ArrayList which has type of int array.
Try this :
ArrayList<int> stockNo = new ArrayList<int>();
ArrayList<String> stockName = new ArrayList<String>();
while(result.next()){
stockNo.add(result.getInt(1));
stockName.add(result.getString(2));
}
You may want to take a look at the Java Persistence API, although it may be a bit more to set up initially it will offer you many advantages down the line. It will avoid having to do much of what you are doing on the return set.

ResultSet Data of every row store in other array index

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;

mySQL jdbc record retrieval inside for-loop in java

this is what i am doing:
String[] output = new String[index.length];
try{
for(int i=0; i<index.length; i++){
Statement st = con.createStatement();
ResultSet res = st.executeQuery(
"SELECT url FROM resources WHERE rid = "+(index[i]);
while(res.next()){
output[i] = res.getString("url"); //<-- this is where exception is thrown
}
} catch(...)
The Method is working but instead of printing the correct url value, it is priting someting like this:
[Ljava.lang.String;#85af80
What does it mean? The url field in mySQL is VarChar, it worked fine with above methods but in this loop why i am getting the above result??
You haven't initialized output[]!
Try this:
String[] output = new String[index.length];
That strange output is caused by printing the array, ie System.out.println(output);
Try this instead:
System.out.println(Arrays.toString(output));
It's kinda lame, but java doesn't automatically print the array contents, it prints the object type and address. The hint is the letter L at the start, which it uses to indicate an array

Categories