Retrieve Multiple value from an arraylist in java - java

I am using ArrayList to Store Time,Bid and, ASK value from the database. And I am unable to access the data from Arraylist in form of row wise like database. how can I do it.
Here is the code:-
List<String> graphData=new ArrayList<String>();
stmt = c.createStatement();
rs = stmt.executeQuery( "SELECT TIME,BID,ASK FROM '"+title+"' ;" );
System.out.println("Opened database successfully 20");
List<Double> buyMap=new ArrayList<Double>();
double buy_avg=0.0, bid=0.0, temp_profit, cum_prof=0;
while(rs.next()){
i++;
graphData.add(rs.getString(1));
graphData.add(df.format(rs.getFloat(2)));
graphData.add(df.format(rs.getFloat(3)));
}
Now how can I get the data from graphData. Because I have to put these value in graph.

Ah, good lord just create an Object.
Example
public class Buy {
private String firstValue;
private String secondValue;
private String thirdValue;
}
Then create a new Buy object with each row from the database..
graphData.add(new Buy(rs.getString(1), df.format(rs.getFloat(2)), df.format(rs.getFloat(3)));
Now you can access it in a pretty way, rather than jumping through an ArrayList in increments of 3.

You can do this:
for (int i=0; i<graphData.size(); i+=3){
// get elem at i
// get elem at i+1
// get elem at i+2
}
But I would recommend you create some bean/POJO object and populate it with
the 3 values from each rs row. Then you add the bean objects to graphData.

How about using a list of lists? In this way, each list would represent a row in the database:
List<List<String>> graphData=new ArrayList<List<String>>();
stmt = c.createStatement();
rs = stmt.executeQuery( "SELECT TIME,BID,ASK FROM '"+title+"' ;" );
System.out.println("Opened database successfully 20");
List<Double> buyMap=new ArrayList<Double>();
double buy_avg=0.0, bid=0.0, temp_profit, cum_prof=0;
while(rs.next()){
i++;
List<String> row = new ArrayList<String>();
row.add(rs.getString(1));
row.add(df.format(rs.getFloat(2)));
row.add(df.format(rs.getFloat(3)));
graphData.add(row)
}
To access the data in a row like manner (akin to how they are stored in the database), you could do something like so:
for(List<String> db : graphData)
{
System.out.println("TIME: " + db.get(0) + " BID " + db.get(1) + " ASK " + db.get(2));
}

Your code:
List<String> graphData=new ArrayList<String>();
stmt = c.createStatement();
rs = stmt.executeQuery( "SELECT TIME,BID,ASK FROM '"+title+"' ;" );
System.out.println("Opened database successfully 20");
List<Double> buyMap=new ArrayList<Double>();
double buy_avg=0.0, bid=0.0, temp_profit, cum_prof=0;
while(rs.next()){
i++;
graphData.add(rs.getString(1));
graphData.add(df.format(rs.getFloat(2)));
graphData.add(df.format(rs.getFloat(3)));
}
retrieve data from list:
for (String string : graphData) {
System.out.println(string); // prints the values of the list
}

Why don't you create a class to hold your data?
public class MyData {
private String field1;
private String field2;
private String field3;
public MyData( String f1, String f2, String f3) {
field1=f1;
field2=f2;
field3=f3;
}
// Add getters
}
Then read data this way:
List<MyData> graphData=new ArrayList<MyData>();
stmt = c.createStatement();
rs = stmt.executeQuery( "SELECT TIME,BID,ASK FROM '"+title+"' ;" );
System.out.println("Opened database successfully 20");
List<Double> buyMap=new ArrayList<Double>();
double buy_avg=0.0, bid=0.0, temp_profit, cum_prof=0;
while(rs.next()){
i++;
graphData.add(new MyData( rs.getString(1), df.format(rs.getFloat(2)), df.format(rs.getFloat(3)));
}
and read it this way:
for ( MyData data : graphData )
{
// do something with data
}

Related

Pulling specific values from a List in Java

I'm pulling data from a database and storing it in a List, right now when I pull a entry from the list using list.get(index) I'm getting an output of {hours_worked=1.5}.
All I want to get from the database is the 1.5 and not the hours worked.
This is the method I'm using that is retrieving the List:
public List totalHoursByActivity(int custId, int activityId) throws ClassNotFoundException, SQLException {
this.openConnection();
List totalHours = new ArrayList();
String sqlStmt = "SELECT hours_worked\n"
+ "from work_entry\n"
+ "JOIN activity\n"
+ "ON work_entry.activity_id = activity.activity_id\n"
+ "JOIN customer\n"
+ "ON work_entry.customer_id = customer.customer_id\n"
+ "WHERE customer.customer_id = " + custId + " and activity.activity_id = " + activityId;
totalHours = db.findRecords(sqlStmt);
return totalHours;
}
Is there a way to go about pulling out just the double from the list? or what might be the best way for pulling that data out and get that value?
Edit: This is what findRecords is:
public List findRecords(String sqlStmt) throws SQLException {
final List allRecords = new ArrayList();
Map record = null;
Statement stmt = null;
ResultSet rs = null;
ResultSetMetaData metaData = null;
stmt = conn.createStatement();
rs = stmt.executeQuery(sqlStmt);
metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
while (rs.next()) {
record = new HashMap();
for (int i = 1; i <= columnCount; i++) {
record.put(metaData.getColumnName(i), rs.getObject(i));
}
allRecords.add(record);
}
return allRecords;
}
Your findRecords returns list of maps and each map holds column name as the key and the corresponding value.
In your case the key is 'work_entry' as suggested by the sql statement,
and the value is 1.5, the {hours_worked=1.5} is the default output of the toString method on the map.
If you want time, you need to call totalHours.get(i).get("hours_worked").
If you used generics you would see the objects types.

Java Netbeans fetching query result into JLabels

I have a JFrame form which asks the user to insert for example his name then it shows him the addresses of all houses he owns (user may own more than one house).
However, since i dunno how many result the query will come out with, i created a function of type vector and stored the data into it, then returned the vector. At the JFrame form i'm doing something like this.
Vector<String> data = User.getHouse(userName.getText());
if (data.isEmpty()) {
JOptionPane.showMessageDialog(null, "No Houses were found!");
}
else {
for(int i=0; i<data.size(); i++)
{
System.out.println(data.elementAt(i));
houses.setText(data.elementAt(i));
houses2.setText(data.elementAt(i+1));
}
}
the function code:
public static Vector<String> getHouse(String playerName) throws SQLException, ClassNotFoundException {
Connection con = DBConnect.getConnection();
PreparedStatement getId = con.prepareStatement("SELECT Player_Id from PLAYERS WHERE Name = ?");
getId.setString(1, playerName);
ResultSet y = getId.executeQuery();
if(y.next())
{
id = y.getString("Player_id");
System.out.println("playerID => " + id);
}
System.out.println("playerName => " + playerName);
PreparedStatement s = con.prepareStatement("SELECT House_Name FROM HOUSES WHERE Player_Id = ?");
s.setString(1, id);
System.out.println("getHouse => Query");
ResultSet x = s.executeQuery();
Vector<String> data = new Vector<String>();
while(x.next())
{
data.addElement(x.getString("House_Name"));
}
return data;
}
(query returns 2 rows). How can i correctly set the JLabel text with the query result?

Getting next value from sequence

I have a bit of code here to get the next value of my sequence, but it is adding the total number of records onto the result each time.
I'm only learning about prepared Statements, I'm thinking this is something small, maybe rset.next() should be something else?
public void add( String title, String actor, String genre ) {
try {
String sql2 = "Select movie_seq.nextval from Movie";
pstmt = conn.prepareStatement(sql2);
rset = pstmt.executeQuery();
int nextVal = 0;
if(rset.next())
nextVal = rset.getInt(1);
String queryString = "Select MovieID, Title, Actor, Genre from Movie";
pstmt = conn
.prepareStatement(queryString,
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rset = pstmt.executeQuery();
rset.moveToInsertRow();
rset.updateInt(1, nextVal);
rset.updateString(2, title);
rset.updateString(3, actor);
rset.updateString(4, genre);
rset.insertRow();
pstmt.executeUpdate();
} catch (SQLException e2) {
System.out.println("Error going to previous row");
System.exit(1);
}
}
Any help appreciated.
I think you don't need the call to pstmt.executeUpdate();
As stated in ResultSet doc, the function insertRow stores the row in the Dataset AND in the database.
The following code shows all that's necessary to add a new row:
rset.moveToInsertRow(); // moves cursor to the insert row
rset.updateString(1, "AINSWORTH"); // updates the
// first column of the insert row to be AINSWORTH
rset.updateInt(2,35); // updates the second column to be 35
rset.updateBoolean(3, true); // updates the third column to true
rset.insertRow();
rset.moveToCurrentRow();
Why dont you iterate using while rather than if . something like this
List lst = new ArrayList();
Someclass sc = new SomeClass(); //object of the class
String query = "SELECT * from SomeTable";
PreparedStatement pstmt = sqlConn.prepareStatement(query);
ResultSet rs = pstmt.executeQuery();
Role role = null;
while (rs.next()) {
String one = rs.getString(1);
String two = rs.getString(2);
boolean three = rs.getBoolean(3);
//if you have setters getters for them
sc.setOne(one);
sc.setTwo(two);
sc,setThree(three);
lst.add(sc)
}
//in the end return lst which is of type List<SomeClass>
}
Shouldn't you be doing this instead?:
String sql2 = "Select " + movie_seq.nextval + " from Movie";
As it is, it seems like you're passing a slightly bogus string into the SQL query, which is probably defaulting to the max index (not 100% positive on that). Then rs.next() is just incrementing that.

Store rows of resultset in array of strings

I want to count the numbers of entries in resultset and then store these values in an array and pass this array to create a graph.
ResultSet rs = stmt.executeQuery( "SELECT distinct "+jTextField.getText()+" as
call from tablename"); // this statement will select the unique entries in a
particular column provided by jtextfield
int count=0;
while(rs.next())
{ ++count; } // This will count the number of entries in the result set.
Now I want to store the values of result set in an array of string. I used the following code
String[] row = new String[count];
while(rs.next())
{
for (int i=0; i <columnCount ; i++)
{
row[i] = rs.getString(i + 1);
}
}
Error : Invalid Descriptor Index.
Please suggest how to copy the result of resultset in array.
For example if I enter priority in jTextField , the result set will contain
priority1
priority2
priority3
In your first while loop you read all the entries in the ResultSet, so when executing the second while loop there's nothing else to read. Also, the index of ResultSet#getXxx starts at 1, not at 0. Also, since you don't know the amount of rows that you will read, it will be better using a List backed by ArrayList instead.
Considering these, your code should look like:
ResultSet rs = stmt.executeQuery( "SELECT distinct "+jTextField.getText()+
" as call from tablename");
List<String> results = new ArrayList<String>();
while(rs.next()) {
results.add(rs.getString(1));
}
Based in your comment, I extended the sample:
public List<String> yourRandomQuery(String columnName) {
Connection con = null;
ResultSet rs = null;
List<String> results = new ArrayList<String>();
try {
String baseQuery = "SELECT DISTINCT %s AS call FROM tablename";
con = ...; //retrieve your connection
ResultSet rs = stmt.executeQuery(String.format(baseQuery, columnName));
while(rs.next()) {
results.add(rs.getString(1));
}
} catch (SQLException e) {
//handle your exception
e.printStacktrace(System.out);
} finally {
closeResource(rs);
closeResource(con);
}
return results;
}
//both Connection and ResultSet interfaces extends from AutoCloseable interface
public void closeResource(AutoCloseable ac) {
try {
if (ac != null) {
ac.close();
}
} catch (Exception e) {
//handle this exception as well...
}
}
public void someMethod() {
//retrieve the results from database
List<String> results = yourRandomQuery(jTextField.getText());
//consume the results as you wish
//basic example: printing them in the console
for(String result : results) {
System.out.println(result);
}
}
Try this
ResultSet rs = stmt.executeQuery( "SELECT distinct "+jTextField.getText()+" as
call from tablename");
List<String> list=new ArrayList<>();
while(rs.next())
{
list.add(rs.getString(1));
}
Why not just create a HashSet<String> and write into that. Note that HashSet is unordered, just like your query. By using a collection that is of arbitrary size you don't need to determine the require dsize in advance.

How to get a particular column's values alone?

I am using the mysql java connector. I need java to display the contents of the first column and the second column in different steps. How do I achieve this?
String qry = "select col1,col2 from table1";
Resultset rs = statement.executeQuery(qry);
I've posted a sample below:
Statement s = conn.createStatement ();
s.executeQuery ("SELECT id, name, category FROM animal");
ResultSet rs = s.getResultSet ();
int count = 0;
while (rs.next ())
{
int idVal = rs.getInt ("id");
String nameVal = rs.getString ("name");
String catVal = rs.getString ("category");
System.out.println (
"id = " + idVal
+ ", name = " + nameVal
+ ", category = " + catVal);
++count;
}
rs.close ();
s.close ();
System.out.println (count + " rows were retrieved");
(From: http://www.kitebird.com/articles/jdbc.html#TOC_5 )
Edit: just re-read the question and think you might mean you want to refer to a column later on in code, instead of in the inital loop as in my example above. In that case, you can create an array and refer to the array later on, or, as another answer suggests you can just do another query.
Load them into any data structure of your choice and then display them to your heart's content.
List<String> firstCol = new ArrayList<String>();
List<String> secondCol = new ArrayList<String>();
while(rs.next()){
firstCol.add(rs.getString("col1"));
secondCol.add(rs.getString("col2"));
}
Then you can manipulate with the two list as you want.
How about ... (insert drumroll here):
String qry1 = "select col1 from table1";
Resultset rs1 = statement.executeQuery(qry);
String qry2 = "select col2 from table1";
Resultset rs2 = statement.executeQuery(qry);
(You might want to phrase your question more clearly.)
You can do it like this :
String sql = "select col1,col2 from table1";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) System.out.println(rs.getString("col1"));
I am using following Code:
Statement sta;
ResultSet rs;
try {
sta = con.createStatement();
rs = sta.executeQuery("SELECT * FROM TABLENAME");
while(rs.next())
{
Id = rs.getString("COLUMN_Name1");
Vid = rs.getString("COLUMN_Name2");
System.out.println("\n ID : " + Id);
System.out.println("\n VehicleID: " + Vid);
}
}
catch(Execption e)
{
}
And this code is 100% working.
String emailid=request.getParameter("email");
System.out.println(emailid);
rt=st.executeQuery("SELECT imgname FROM selection WHERE email='emailid'");
System.out.println(rt.getString("imgname"));
while(rt.next())
{
System.out.println(rt.getString("imgname"));
finalimage=rt.getString("imgname");
}

Categories