I have String ArrayList to compare against Resultset.
Ex: ArrayList Elements
ITM001
ITM002
ITM003
ITM004
Ex: Resultset 1
ITM001
ITM002
ITM003
ITM004
Contains all elements
return ArrayList Empty;
Ex: Resultset 2
ITM001
ITM002
ITM004
Missing ITM003
return ArrayList ITM003;
Ex: Resultset 3
ITM001
ITM002
Missing ITM003, ITM004
return ArrayList ITM003,ITM004;
If Resultset does not contain all elements of Arraylist, those missing
elements must return as an ArrayList. Else return empty ArrayList.
This is what I tried.
public static ArrayList<String> checkStoreItems(String currentStore, ArrayList<String> stlist) throws ClassNotFoundException, SQLException {
Connection conn = DBConnection.conn();
String sql = "select itemId from Store_Items where storeID=(select storeID from StoreMain where locationName=?)";
Object []values ={currentStore};
ResultSet res = DBHandller.getData(sql, conn, values);
ArrayList<String> storelist = new ArrayList<String>();
while(res.next()){
String item = res.getString("itemId");
for (int i = 0; i < stlist.size(); i++) {
if (item.contains(stlist.get(i))) {
continue;
}else{
storelist.add(item);
}
}
}
return null;
}
If I understood your question correctly , you can try something like this :
public static ArrayList<String> checkStoreItems(String currentStore,
ArrayList<String> stlist) throws ClassNotFoundException, SQLException {
Connection conn = DBConnection.conn();
String sql = "select itemId from Store_Items where storeID=(select storeID from StoreMain where locationName=?)";
Object []values = {currentStore};
ResultSet res = DBHandller.getData(sql, conn, values);
Set<String> storelist = new HashSet<String>();
while(res.next()){
String item = res.getString("itemId");
storelist.add(item);
}
stlist.removeAll(storelist);
return stlist;
}
Use HashSet's removeAll method to perform the operation. You will first need to put the elements from each source into a HashSet.
This avoids the need to loop over the entire ArrayList for every element in the ResultSet making it an O(n) operation, instead of O(n^2).
ArrayList<String> diffResultSet(Collection<String> coll, ResultSet resultSet, int column) {
Set<String> collSet = new HashSet<String>(coll);
Set<String> resultSetSet = new HashSet<String>();
while (resultSet.next()) {
resultSetSet.add(resultSet.getString(column));
}
collSet.removeAll(resultSetSet);
return new ArrayList<String>(collSet);
}
Related
I am retrieving the data from database and want to return it to calling function in the form of Map.
But the issue i am facing here is that the value in form_dtl array gets overrided by the last value.
DB structure is as follows :-
base_mainid form_id form_link form_name
1 1 .//*[#id='collapse-text-dynamic-form-number WC1
1 2 .//*[#id='collapse-text-dynamic-form-number WC3
1 3 .//*[#id='collapse-text-dynamic-form-number WC6
1 4 .//*[#id='collapse-text-dynamic-form-number WC15
How to resolve this ?
public static Map formXPath(int formid)
{
int form_id = -1;
Statement s3 = null;
String[] form_dtl = new String[2];
try {
s3 = con.createStatement();
String query = "SELECT form_id,form_link,form_name FROM form_details where base_mainid = " + formid;
ResultSet rs2 = s3.executeQuery(query);
while (rs2.next()) {
form_id = rs2.getInt(1);
form_dtl[0] = rs2.getString(2);
form_dtl[1] = rs2.getString(3);
// System.out.println("ID : "+formid+" Name : "+form_dtl[2]);
form.put(form_id, form_dtl);
}
return form;
Try this way, instanciate your form_dtl array inside the loop so that you have a new one at every iteration. If not, you are always using the same one and the values get overriden.
public static Map<Integer, String[]> formXPath(int formid) {
Map<Integer, String[]> form = new HashMap<>();
int form_id = -1;
Statement s3 = null;
String[] form_dtl;
try {
s3 = con.createStatement();
String query = "SELECT form_id,form_link,form_name FROM form_details where base_mainid = " + formid;
ResultSet rs2 = s3.executeQuery(query);
while (rs2.next()) {
// instanciate here
form_dtl = new String[2];
form_id = rs2.getInt(1);
form_dtl[0] = rs2.getString(2);
form_dtl[1] = rs2.getString(3);
form.put(form_id, form_dtl);
}
} catch(Exception e) { /* Handle exception here */ }
return form;
}
Your values are overrided because you are saving the information in the same place for every step in the while loop.
while (rs2.next()) {
form_id = rs2.getInt(1);
form_dtl[0] = rs2.getString(2);
form_dtl[1] = rs2.getString(3);
form.put(form_id, form_dtl);
}
Every time you execute the loop (in this case with the DB contents, four times) you are overriden the values in form_dtl.
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
}
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().
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.
I am trying to get all the results from multiple rows returned by the same where condition:
public static String getResult(String mycondition)
{
ResultSet rsData = sql.RunSelect("select col1 from my_table where con ='"+myCondition+"'");
if (rsData.next())
{
String result = rsData,getString("col1");
}
}
Note that there is an id column that makes these rows distinguishable.
The display in jsp page should make text fields for every row returned.
Any thoughts?
You can return a List<String> or use a char to separate the multiple strings in a single String. IMO it would be better returning a List<String>:
public static List<String> getResult(String mycondition) {
List<String> results = new ArrayList<String>();
ResultSet rsData = sql.RunSelect("select col1 from my_table where con='"
+myCondition+"'");
while (rsData.next()) {
results.add(rsData.getString("col1"));
}
return results;
}
Also, this method is prone to SQL Injection. Note that your parameters should be sent apart from the query. Probably you can improve your sql.RunSelect method to use PreparedStatement instead of Statement. This is a basic example of the code skeleton:
public ResultSet runSelect(String query, Object ... params) {
//assumes you already have your Connection
PreparedStatement pstmt = con.prepareStatement(query);
int i = 1;
for(Object param : params) {
pstmt.setObject(i++, param);
}
return pstmt.executeQuery();
}
So now you could modify your method to
public static List<String> getResult(String mycondition) {
List<String> results = new ArrayList<String>();
//using the new runSelect method
ResultSet rsData = sql.runSelect(
"select col1 from my_table where con=?", mycondition);
while (rsData.next()) {
results.add(rsData.getString("col1"));
}
return results;
}
you should use while loop instead of if loop
instead of - if (rsData.next())
use - while (rsData.next())
Although answer of #Luiggi Mendoza is best if you want security in your code