Retrieving records from MySQL in Java
I'm building an application in Java to retrieve data from MySQL database. After executing a query I get a ResultSet and do the following to extract records:
while (rs.next())
{
for (int column = 1; column <= rm.getColumnCount(); column++) {
row.add(rs.getObject(column));
}
result.add(row.toString());
row.clear();
}
where rs = ResultSet and rm = ResultSetMetaData
The problem is that I have to do result.add(row.toString()); rather than just result.add(row); (with which I'd like to create a two-dimensional ArrayList). Otherwise I get empty results.
I have tried putting row.clear(); at the beginning, before the for loop, but that results in all my results being filled with multiple instances of the last record. Just like row was not added to the result until the very end, when it's equal to the last record. Do I need to "commit" the ArrayList row before adding it as an elemt to another ArrayList? If so, how? Also, out of curiosity, why is .toString() working differently?
Asked by: Carlos825 | Posted: 23-01-2022
Answer 1
By adding row.toString(), you're creating a new String object to add into result.
On the other hand, by adding row, you're adding the same object into result, therefore, each time row.clear() is called, it empty all the rows in result.
What you should do is to create a new row object before the for loop, and don't do row.clear(). Following is an example.
while (rs.next())
{
row = new ArrayList();
for (int column = 1; column <= rm.getColumnCount(); column++) {
row.add(rs.getObject(column));
}
result.add(row);
}
Answered by: Cadie908 | Posted: 24-02-2022
Similar questions
java - What will happen if records are deleted during the data retrieving process?
Let's say I have 6 records, and I set the fetch size as 2.
[Id] [Name]
11 A <-- 1st fetch, start from 1 position
21 B
31 C <-- 2nd fetch, start from 3 position
41 D
51 E <-- 3rd fetch, start from 5 position
61 F
If 1st user issues a "SELECT * from tablex", and 2nd user issue a "DELETE FROM tablex WHERE Id = 2. The deletion process happen just in time betwee...
java - Retrieving records from a hashmap
I have 2 forms , one form for registration and other form for searching records,deleting,etc.
In the registration form i put the registration details in to an object and then store it in a hashmap. In the second form i access the hashmap to delete ,search records according to the id saved(Key).
My problem is when i save a record and access it from the second form (access the hashmap), i get null pointer exception....
java - Retrieving next N records in mongo db
Closed. This question does not meet Stack Overflow guid...
java - Saving and retrieving records in two related tabls wiht JPA
In my application there are two models with @onetomany realationship.
I have defined Room and Seat entities. My first problem is that seats collection always returns null.
@Entity
public class Room implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long Id;
private String name;
@OneToMany(mappedBy = "room")
Set<Seat> seats = new HashSe...
java - retrieving latest records From Table (Table having 3 dates column)
I have a doubt.If a table is having 3 dates columns then how to retrieve latest records from the table by comparing the three dates.Is it possible to retrieve the records in sql.
i need latest 10 records which is having the latest date among the 3 columns
java - select JDBC query not retrieving records in order
I am trying to fetch records from oracle db. I have a select query which has an order by clause implemented. Now when I fire the query on the toad i get the results in correct order. i.e the order of the records at 10:00 AM is like
Record 1, Record 2,Record 3 and at 10:05 its Record 1, Record 2, Record 3. This is what i need.
Now when iam fetching it through java code, JDBC . I try to iterate the resultset, but he...
Retrieving all records from a atable using java JPQL
I am trying to write a simple query using JPQ to retrieve all the rows in a table. I believe I have set up my entity up correctly as well as my persistence unit as the tables were successfully created on deployment of the module. My issue is that when I try to retrieve anything from the table it does not work.
The code in my EJB to retrieve the rows looks like this:
@Override
public List<Car>...
java - Saving / Retrieving list or records in/ from REDIS Cache
I have a data (as per below) which is stored in a POJO (EquityFeeds):
externalTransactionId,clientId,transactionType,transactionDate,marketValue,sourceSystem,priorityFlag,processingFee
SAPEXTXN1,GS,BUY,23/11/13,101.9,BLO,Y,0
SAPEXTXN2,AS,SELL,20/11/13,121.9,BLO,N,0
SAPEXTXN3,AP,DEPOSIT,19/11/13,120,BLO,Y,0
SAPEXTXN4,HJ,WITHDRAW,30/11/13,230,BLO,N,0
SAPEXTXN5,GS,WITHDRAW,26/11/13,330,BLO,Y,0
SAPEXTXN6,AP,SEL...
java - Problem retrieving properties file from webapp in tomcat
I've developed a web application that worked fine in JBoss 4. Now, I need to make it work in Tomcat 6, but I'm having trouble to access some properties file. I use the following code to read read these files:
InputStream is = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(fileName);
if (is == null) {
throw new StartupError("Error loading " + fileName);
}
properties....
java - What will happen if records are deleted during the data retrieving process?
Let's say I have 6 records, and I set the fetch size as 2.
[Id] [Name]
11 A <-- 1st fetch, start from 1 position
21 B
31 C <-- 2nd fetch, start from 3 position
41 D
51 E <-- 3rd fetch, start from 5 position
61 F
If 1st user issues a "SELECT * from tablex", and 2nd user issue a "DELETE FROM tablex WHERE Id = 2. The deletion process happen just in time betwee...
java - Retrieving the SMS Messages from the SIM card on with android
I was wondering if anyone knew anything about programmatically getting the sms messages off of your phone's sim card on an android platform. I would like to write a program that allows you to save either individual messages or entire threads to the sd card, but after looking around for a bit, I have discovered that google decided to take out that api from the current android sdk. I saw in a few places that there are hidden...
java - How to avoid OOM (Out of memory) error when retrieving all records from huge table?
I am given a task to convert a huge table to custom XML file. I will be using Java for this job.
If I simply issue a "SELECT * FROM customer", it may return huge amount of data that eventually causing OOM. I wonder, is there a way i can process the record immediately once it become available, and remove the record from memory after that during sql retrieving process?
--- edited on 13 Jul 2009
Let me...
java - Retrieving the logged in user's name and hostname in Windows
I'm currently writing a Java application to be used with a Windows-Machine authed with an ActiveDirectory. The application basically only needs to know the user's name and hostname. I know there are
System.getProperty("user.name")
and
java.net.InetAddress.getLocalHost().getHostName()
But I am not sure wether System.getProperty("user.name") will function correctly wi...
c - Retrieving byte array of unknown length from Java store
I already posted a question regarding it, but at that time I haven't have the account. I got a reply but I was still confused and I cannot continue on that thread.
I am re posting the question again along with a link to previous conversation.
Returning char array from java to string - JNI
java - Retrieving information about an Image
Good day,
Anybody knows of a good java library for retrieving mime type and dimension of a jpeg, gif, and png image file in java?
I tried javax.imageio.ImageIO but it seems that there are some image files that it can't handle (i.e. images created with adobe photoshop).
Thanks,
Franz
sql - Java - retrieving large amounts of data from a DB using iBatis
I need to extract data from a DB2 table, run some processing on each returned row and output to a flat file. I'm using iBatis but found that using the queryForList I started getting out of memory errors, I'll be looking at 100k+ rows of data increasing.
I've looked at using queryWithRowHandler instead but the iBatis RowHandler interface ...
java - What is the best practice for retrieving an item in a collection from a domain model?
What is the best practice for retrieving an object from a collection within a domain object with a specified property?
For example, we have a car insurance application which has two classes: a Person with a list of Cars. If I always needed to retrieve a Car from a Person with the specified VIN, what is the best way to implement the method? I've provided a few examples below - others are welcome
Ex...
Java - Retrieving amount of types in list
I have a list. The list can contain multiple items of the same enum type.
Lets say i have an enum : TOY which has values: BALL, DOLL, PLAYSTATION. I want to know how many PLAYSTATION items are in a list with the type TOY. (ie, List<Toy> toys)
What is the best possible solution for this? I don't want to keep ite...
Still can't find your answer? Check out these amazing Java communities for help...
Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)