Store rows of resultset in array of strings - java

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.

Related

Update one column from table and insert new rows. sqlite, java

I have some problems to modify data from a table.
I need to update an entire column from a specific table and if there's no sufficient rows I need to insert more.
More exactly, the user will be able to modify data from interface, in a text area that contains current data from db.
I put all the text in a list, each line representing an element of the list.
In a certain column, I must go through each row and modify it with a list item. If there are more lines in the text area than number of rows in that table, I need to insert new ones, which will contain the remaining items from the list.
I would be grateful if someone could give me some help.
Thanks!
#FXML
public void modify() throws SQLException {
String col= selectNorme.getValue().toString();
String text=texta.getText();
List<String> l1notes= new ArrayList<>( Arrays.asList( text.split("\r\n|\r|\n") ));
Statement stmt=null;
String client = this.clientCombobox.getValue().toString();
String tab1Client= client+ "_" +this.selectLang1.getValue().toString();
String query="SELECT * FROM "+tab1Client+" WHERE ["+ selectNorme.getValue().toString()+ "]= "+col+"";
String sqlUpdate1= "UPDATE ["+tab1Client+"] SET ["+ this.selectNorme.getValue().toString() +"] = ?";
try {
Connection conn = dbConnection.getConnection();
PreparedStatement modif=conn.prepareStatement(sqlUpdate1);
int i=0;
if (rss.next()) {
stmt = conn.createStatement();
rss = stmt.executeQuery(query);
stmt.executeUpdate(sqlUpdate1);
modif.setString(1, l1notes.get(i));
i++;
modif.execute();
}
else {
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO ["+this.clientCombobox.getValue().toString()+"_"+this.selectLang1.getValue().toString()+"] (["+ this.selectNorme.getValue().toString() +"]) values (?)" );
for (int row=i; row< l1notes.size(); row++)
{
pstmt.setString(1, l1notes.get(row));
pstmt.executeUpdate();
}
}
}
finally {
try {
if (conn !=null)
conn.close();
}
catch (SQLException se){
se.printStackTrace();
}
}
}

List won't add other ResultSet even it's already given

I'm adding all the ResultSet in my List <EmployeeModel. I successfully retrieve all rows. But when it comes to adding all rows in List it only gets the first row and the loop already skip another row to be added. Any reasons why?
public void getStartEndTimeForOvertime(EmployeeModel employeeModel)
{
String query = "{call getStartEndTimeForOvertime(?,?)}";
List <EmployeeModel> list = new ArrayList();
try(Connection con = DBUtil.getConnection(DBType.MYSQL);
CallableStatement cs = con.prepareCall(query);)
{
cs.setInt(1, EmployeeModel.getId());
cs.setString(2, employeeModel.overtimeModel.getDay());
try(ResultSet rs = cs.executeQuery())
{
while(rs.next())
{
employeeModel.overtimeModel.setStartTime(rs.getString(1));
employeeModel.overtimeModel.setEndTime(rs.getString(2));
list.add(employeeModel);
}
}
}
catch(SQLException ex)
{
System.out.println("Error at getStartEndTimeForOvertime: "+ex.getSQLState());
System.out.println("Error at getStartEndTimeForOvertime: "+ex.getMessage());
System.out.println("Error at getStartEndTimeForOvertime: "+ex.getErrorCode());
}
}
While iterating through the resultSet, everytime you are setting it on the same object of EmployeeModel
Instead do this
while(rs.next()){
EmployeeModel employeeModel = new EmployeeModel();
employeeModel.overtimeModel.setStartTime(rs.getString(1));
employeeModel.overtimeModel.setEndTime(rs.getString(2));
list.add(employeeModel);
}

Prepare statement inside a loop

I trying execute a query inside a loop.I am tryning this code :
public List<Products> DisplayProducts(String []a)
{
ResultSet rs = null;
List<Products> Data=null;
try
{
for(int i=0;i<a.length;i++)
{
String query = "select * from products where Brand=?";
PreparedStatement stmt=DataBaseConnection.DBConn.getConnection().prepareStatement(query);
stmt.setString(1, a[i]);
rs=stmt.executeQuery();
}
if(rs.next())
{
rs.beforeFirst();
Data=new ArrayList<Products>();
while(rs.next())
{
Products p=new Products();
p.setTitle(rs.getString(2));
p.setCategory(rs.getString(3));
p.setSubCategory(rs.getString(4));
p.setSubCategoryTwo(rs.getString(5));
p.setPrice(rs.getInt(6));
p.setFlavour(rs.getString(7));
p.setImage(rs.getString(8));
p.setBrand(rs.getString(9));
p.setInstock(rs.getString(10));
p.setInstockQty(rs.getInt(11));
Data.add(p);
}
}
return Data;
}
catch(Exception e)
{
System.out.println(e.getStackTrace());
return null;
}
}
I have a jsp page where I have Checkboxes and I am displaying multiple products on this page. I am sorting this products by BRANDS. User selects Brand by checking checkbox.
I am passing the value of checkbox to a servlet and on that servlet calling function Display Products:
String arr[]=request.getParameterValues("On");
List<Products> Data=new SessionBeanClass().DisplayProducts(arr);
Please tell me how do I execute this and get the result ?
I suppose you need to return the list of all products with the checkbox ticked. In that case i suppose you have a logic error here. This method only returns the last Product record.
Instead of looping through different id you could use 'IN' clause and return all at once. There are many differet ways to achieve IN clause. The one given below is a simple alternative. You could check for various operations in http://www.journaldev.com/2521/jdbc-preparedstatement-in-clause-alternative-approaches or http://www.javaranch.com/journal/200510/Journal200510.jsp#a2
In addition to that try following java naming conventions and clean up connections using finally
Try
public List<Products> DisplayProducts(String[] a) {
ResultSet rs;
List<Products> data;
PreparedStatement stmt;
try {
StringBuilder param = new StringBuilder();
for(String str : a){
param.append("'").append(str).append("', ");
}
String query = "select * from products where Brand in (" + param.substring(0, param.length() - 2) + ")";
stmt = DataBaseConnection.DBConn.getConnection().prepareStatement(query);
rs = stmt.executeQuery();
if (rs != null) {
data = new ArrayList<Products>();
while (rs.next()) {
Products p = new Products();
p.setTitle(rs.getString(2));
p.setCategory(rs.getString(3));
p.setSubCategory(rs.getString(4));
p.setSubCategoryTwo(rs.getString(5));
p.setPrice(rs.getInt(6));
p.setFlavour(rs.getString(7));
p.setImage(rs.getString(8));
p.setBrand(rs.getString(9));
p.setInstock(rs.getString(10));
p.setInstockQty(rs.getInt(11));
data.add(p);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
stmt.close();
}
return data;
}
Explanation as per comment
Ok. I suppose your idea here is to pass a set of brand names say adidas, nike, etc.. and select all the product details. So you need to do something like select * from products where Brand in ('adidas', 'nike'). This will give you all the products. So for this you pass the selected brand names as a string array. So what i did was to get the values from array and format it and make it as argument for IN clause. So of IN clause it needs comma separated values. Since its a Sting we need to give single quote ' as well. So from an array [adidas, nike] i need to construct 'adidas', 'nike'. That is what done in the for loop, appending ' and , (comma). So after for loop we'll have an additional comma and space at the end (e.g. 'adidas', 'nike', ). In order to remove this i remove the last two charaters by taking substring as param.substring(0, param.length() - 2). This is fed to the query and retrieve the result.

From an ArrayList to a String [] [duplicate]

This question already has answers here:
Convert ArrayList<String> to String[] array [duplicate]
(6 answers)
Closed 9 years ago.
I've implemented a method that return the result of a query on a SQL database.
I just want the method to retur only a String[] which is the result of a query that select a column on the db.
Here my code:
public class DBConnection {
private static Connection con;
private static Statement st;
private static ResultSet rs;
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/database","user","password");
st = con.createStatement();
}
catch (Exception ex)
{
System.out.println("Error: "+ex);
}
public ArrayList<String[]> doQuery (String query)
{
ArrayList<String[]> v = null;
String [] record;
int columns = 0;
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
v = new ArrayList<String[]>();
ResultSetMetaData rsmd = rs.getMetaData();
columns= rsmd.getColumnCount();
while(rs.next()) {
record = new String[columns];
for (int i=0; i<colonne; i++) record[i] = rs.getString(i+1);
v.add( (String[]) record.clone() );
}
rs.close();
stmt.close();
} catch (Exception e) { e.printStackTrace(); }
return v;
}
this method return an ArrayList object that contains the result of a query.
Now, the question is: how can I have from this ArrayList object a String[] object that contains ONLY a column of the result?
(As information : The String[] object will be inserted in a JComboBox object)
I assume your question has two components: a) you want to return a string array and b) you want to return only a single column.
The answer to a) has already been given or at least hinted at.
The answer to b) would require you to know the name of the column you want to return or adjust the query.
You might change your method to something like this:
public String[] doQuery (String query, String columnName) //columnName not needed if you know the index of the column or if the name is always the same, in which case it could be some constant
{
List<String> v = new ArrayList<String>();
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next()) {
v.add( rs.getString(columnName) ); //or rs.getString(1); if you know the column is the first in the query's result
}
rs.close();
stmt.close();
} catch (Exception e) { e.printStackTrace(); }
return v.toArray(new String[v.size()]);
}
A few notes:
You'd have to ensure that the column has the name you want to query it with, i.e. you can't do select columnA from ... and then call rs.getString("columnB");. If you don't know the name but know the index of the column in the resultset, use rs.getString(x); instead, where x is the one-based index.
instead of v.toArray(new String[v.size()]); you could also use v.toArray(new String[0]);. The difference between the two is that the former returns the array you pass as a parameter whereas the latter creates a new array internally and returns that.
why not to call v.toArray(new String[0])?
pasted the solution given in link Converting 'ArrayList<String> to 'String[]' in Java
ArrayList<String> list = new ArrayList<String>();
String[] array = list.toArray(new String[list.size()]);
(or)
ArrayList<String> arrayList = new ArrayList<String>();
Object[] ObjectList = arrayList.toArray();
String[] StringArray = Arrays.copyof(ObjectList,ObjectList.length,String[].class);
On an ArrayList you can call toArray() to get an Array of its values.
This would look like this:
// create an ArrayList
ArrayList<String> theArrayList = new ArrayList<String>();
theArrayList.add("aString");
theArrayList.add("anotherString");
// get its contents as an Array
String[] theArray = new String[theArrayList .size()];
theArray = theArrayList.toArray(theArray);
You can look up more details in the Java Docu for ArrayList.toArray().

ArrayList keep returning 0

I retrieve the data from database and loop it thru an array to display the like amount.
public void SetUpLikeAmount() {
int likes = 0;
ArrayList <Integer> likeArray = new ArrayList <Integer>();
for (int count = 0; count < likeArray.size();count++){
// Set Up Database Source
db.setUp("IT Innovation Project");
String sql = "Select likeDislike_likes from forumLikeDislike WHERE topic_id = "
+ topicId + "";
ResultSet resultSet = null;
// Call readRequest to get the result
resultSet = db.readRequest(sql);
try {
while (resultSet.next()) {
likeArray.add(Integer.parseInt(resultSet.getString("likeDislike_likes")));
likes += likeArray.get(count);
}
resultSet.close();
} catch (Exception e) {
System.out.println(e);
}
}
jLabel_like.setText(Integer.toString(likes));
}
However, it keeps returning 0. Thanks in advance.
(As an aside, it never returns anything - you've posted a void method.)
Look at this code:
ArrayList <Integer> likeArray = new ArrayList <Integer>();
for (int count = 0; count < likeArray.size();count++){
...
}
You've just created a new ArrayList<Integer>, which will therefore have a size of 0. Therefore, the loop always completes immediately, without ever executing the body.
If you're trying to get input from a list created elsewhere, you should probably pass that into your method. (You should also use a PreparedStatement with a parameter instead of including the value directly in your SQL.)
You're iterating over the list likeArray which is empty. So it won't enter the loop
May be here is the new code you should refer:
public void SetUpLikeAmount() {
int likes = 0;
// Set Up Database Source
db.setUp("IT Innovation Project");
String sql = "Select likeDislike_likes from forumLikeDislike WHERE topic_id = "
+ topicId + "";
ResultSet resultSet = null;
// Call readRequest to get the result
resultSet = db.readRequest(sql);
try {
while (resultSet.next()) {
likes += Integer.parseInt(resultSet.getString("likeDislike_likes"));
}
resultSet.close();
} catch (Exception e) {
System.out.println(e);
}
jLabel_like.setText(Integer.toString(likes));
}
You might not need the arraylist I believe as you are getting the value and summing it during the iteration over the result set only.

Categories