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().
Related
So essentially, I am using java to obtain information, and then I am using Kotlin to manage the information. So what I have done so far is, I have stored my information into a ArrayList called tableData in java, I store all my elements into this list (I should have used a better name here) and then returned the list. My java code:
public static ArrayList<String> readAllData () {
//Connecting to database
Connection con = DbConnection.connect();
//Preparing statement
PreparedStatement ps = null;
//result set declaration
ResultSet rs = null;
//tableData String array
ArrayList<String> tableData = new ArrayList<String>();
try {
//Database initialization
String sql = "SELECT * FROM ProjectInfo";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
//for each iteration store the data into variable a from column projectName
String a = rs.getString("projectName");
//print out each element
//System.out.println("a = " + a);
tableData.add(a);
}
//other catch exceptions
} catch (SQLException e) {
System.out.println(e.toString());
} finally {
try {
rs.close();
ps.close();
con.close();
} catch (SQLException e){
System.out.println(e.toString());
}
}
//System.out.println(tableData);
//return all the data that has been stored into this array
return tableData;
}
In Kotlin, I created a property class called GettingData and passed one parameter projectName: ArrayList<String>. Then i moved onto actually printing out the data
class GettingData(var projectName: ArrayList<String>) {
}
fun ManageData() {
var arrayData = listOf<GettingData>(GettingData(DbConnection.readAllData()))
var projectNameData = arrayData.map {it.projectName}
for (projectName in projectNameData) {
println(projectName)
}
}
All my elements are printed out, however I cannot use the filter functions to call specific elements from the arrayList? I want to be able to call every element and print them out in a alphabetical order? I tried filter, sortedWith and find functions but I cannot seem to get it working. How can I achieve this?
I think your question boils down to wanting to print a list of strings in alphabetical order.
You can use the sorted() function:
for (projectName in projectNameData.sorted()) {
println(projectName)
}
what i am trying to do is return a java List of objects of any type that calls the method.
List<Playlist> playlist = Table.selectAll();
Those java objects (in this case Playlist) should each contain a row of values from my SQL ResultSet.
public class Table extends Database {
public List<this> selectAll() {
List<this> newList = new List<this>();
String tableName = this.getClass().getSimpleName().toLowerCase();
Field[] fields = this.getClass().getDeclaredFields();
Connection connection = getConnection();
PreparedStatement preStat = null;
ResultSet resultSet = null;
try {
preStat = connection.prepareStatement("SELECT * FROM " + tableName);
resultSet = getFromDB(preStat);
} catch (SQLException e) {
e.printStackTrace();
}
// create a list of Objects of class ‘this’ (in this case Playlist)
// and using the fields obtained from .getDeclaredFields()
// assign values to each Object from the ‘preStat’ results
// then put those objects into ‘newList’
return newList;
}
}
What am I doing wrong here? should I pass in a List to the method instead of getting a return back, but then how would I create an Object from each ResultSet, assign it values using .getDeclaredFields() then assign the object to the List?
List<this> newList = new List<this>();
is not going to work, it must be
List<PlayList> newList = new List<>();
Then in your comments do
while (resultSet.next()) {
PlayList l = new PlayList();
l.setId(resultSet.getInt(1));
l.setYourStringField(resultSet.getString(2));
l.setAnotherStringField(resultSet.getString(3));
newList.add(l);
}
resultSet.close();
preStat.close();
connection.close();
Being setId, setYourStringField and setAnotherStringField property setters of your PlayList object.
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 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);
}
I have to make a 'query' method for my class which accesses MySQL thru' JDBC.
The input parameter to the method is a full SQL command (with values included), so I don't know the names of columns to fetch out.
Some of the columns are strings, some others are integers, etc.
The method needs to return the value of type ArrayList<HashMap<String,Object>>
where each HashMap is 1 row, and the ArrayList contains all rows of result.
I'm thinking of using ResultSet.getMetaData().getColumnCount() to get the number of columns then fetch cell by cell out of the current row, but is this the only solution? any better ones?
I have the example code here, just in case anybody need it. ('Con' in the code is the standard JDBC connection).
//query a full sql command
public static ArrayList<HashMap<String,Object>>
rawQuery(String fullCommand) {
try {
//create statement
Statement stm = null;
stm = con.createStatement();
//query
ResultSet result = null;
boolean returningRows = stm.execute(fullCommand);
if (returningRows)
result = stm.getResultSet();
else
return new ArrayList<HashMap<String,Object>>();
//get metadata
ResultSetMetaData meta = null;
meta = result.getMetaData();
//get column names
int colCount = meta.getColumnCount();
ArrayList<String> cols = new ArrayList<String>();
for (int index=1; index<=Col_Count; index++)
cols.add(meta.getColumnName(index));
//fetch out rows
ArrayList<HashMap<String,Object>> rows =
new ArrayList<HashMap<String,Object>>();
while (result.next()) {
HashMap<String,Object> row = new HashMap<String,Object>();
for (String colName:cols) {
Object val = Result.getObject(colName);
row.put(colName,val);
}
rows.add(row);
}
//close statement
stm.close();
//pass back rows
return tows;
}
catch (Exception ex) {
System.out.print(ex.getMessage());
return new ArrayList<HashMap<String,Object>>();
}
}//raw_query