I am trying to read data from my MySQL database into an array so that I can output the data in a view.
My code so far is :
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/database","localhost","root");
PreparedStatement stmt = con.prepareStatement("select * from stock");
ResultSet result = stmt.executeQuery("select * from stock");
ArrayList<int[]> stockNo = new ArrayList<int[]>();
ArrayList<String[]> stockName = new ArrayList<String[]>();
while(result.next()){
stockNo.add(result.getInt(1));
stockName.add(result.getString(2));
}
}
However I am getting an error message on the .add the method saying
"the method add(int,int[]) in the type ArrayList is not applicable for the arguements (int)".
Does anyone know how I can fix this? Is it because I havent defined the size of my arrays?
It's because you defined your List for storing arrays of ints, not ints.
Replace this:
ArrayList<int[]> stockNo = new ArrayList<int[]>();
By this:
ArrayList<Integer> stockNo = new ArrayList<Integer>();
result.getInt(1) and result.getString(2) return Integer and String respective. You can not add to ArrayList which has type of int array.
Try this :
ArrayList<int> stockNo = new ArrayList<int>();
ArrayList<String> stockName = new ArrayList<String>();
while(result.next()){
stockNo.add(result.getInt(1));
stockName.add(result.getString(2));
}
You may want to take a look at the Java Persistence API, although it may be a bit more to set up initially it will offer you many advantages down the line. It will avoid having to do much of what you are doing on the return set.
Related
My Code
public static ArrayList getTablesMetadata() throws SQLException{
String table[] = {"TABLE"};
ResultSet rs = null;
ArrayList tables = null;
rs = metadata.getTables(null, null, null, table);
tables = new ArrayList();
while(rs.next()){
tables.add(rs.getString("TABLE_NAME"));
}
return tables;
}
public static void getColumnsMetadata(ArrayList tables)
throws SQLException{
ResultSet rs = null;
for(String actualTable : tables){ <-----------------------------------
rs = metadata.getColumns(null, null, actualTable, null);
System.out.println(actualTable.toUpperCase());
while(rs.next()){
System.out.println(rs.getString("COLUMN_NAME")+ " "
+ rs.getString("TYPE_NAME")+ " "
+ rs.getString("COLUMN_SIZE"));
}
System.out.println("\n");
}
}
Error is pointed out with the arrow, what im getting is:
Type mismatch: cannot convert from element type Object to String
I have tried adding the to certain parts but think im doing it wrong, or something is wrong in the code that I cant seem to see.
ArrayList uses Generics.
Your table variable is a list of Object since the generic type was not specified. You can:
Cast each table object to String
Use ArrayList<String> instead (recommended)
If you don't specify the array list type, it is assumed to hold Object.
try
getColumnsMetadata(ArrayList<String> tables)
I guess you'll also need to change:
tables = new ArrayList<String>();
and change the return value of getTablesMetadata() to
ArrayList<String>
I try a lot of time to solve this so thank you for any help.
How to use array in preparestatement? I do it like in this example How to use an arraylist as a prepared statement parameter but it return me error, my code:
//initialize
ResultSet rs2;
connection2 = sqliteConnection.dbConnector();
PreparedStatement statement2=connection2.prepareStatement("SELECT surname FROM users where id IN (?)");
//like in the example linked, but it did not work:
Array array = connection2.createArrayOf("VARCHAR", new Object[]{"1", "2"});
statement2.setArray(1, array);
rs2=statement2.executeQuery();
//to keep data from resultset, it works fine
List<String> rsDATA = new ArrayList<String>();
while(rs2.next()){
rsDATA.add(rs2.getString("surname"));
}
for(int i = 0; i < rsDATA.size(); i++) {
System.out.println(rsDATA.get(i));
}
connection.close();
but it return error:
Exception in thread "AWT-EventQueue-0" java.lang.AbstractMethodError: org.sqlite.SQLiteConnection.createArrayOf(Ljava/lang/String;[Ljava/lang/Object;)Ljava/sql/Array;
at lines:
1)Array array = connection2.createArrayOf("VARCHAR", new Object[]{"1", "2"});
2(executeQuery();
It is very important for me to solve this. Thank you a lot..
You need to use IN in your WHERE clause:
SELECT surname FROM users WHERE id IN (?)
and a java.sql.Array object as shown in the answer to the linked question.
First ever question here, complete newbie so try to take it easy on me. I'm trying to figure out what's wrong here:
public List<String[]> idOnlyQuery(String searchTerm, Connection conn){
List<String[]> result = new ArrayList<String[]>();
String[] rowResult = new String[7];
Statement stmt = null;
try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT * FROM Jets WHERE CurrentID LIKE '" + searchTerm + "%'");
while(rs.next()){
String currentId= rs.getString("CurrentId");
String manufacturer = rs.getString("Constructor");
String type = rs.getString("ACType");
String series = rs.getString("Series");
String index = rs.getString("KeyNo");
String operator = rs.getString("Operator");
String baseAirport = rs.getString("Home_Airfield");
rowResult[0] = (currentId);
rowResult[1] = (manufacturer);
rowResult[2] = (type);
rowResult[3] = (series);
rowResult[4] = (operator);
rowResult[5] = (baseAirport);
rowResult[6]= (index);
result.add(rowResult);
}
System.out.println(result.get(0)[0]);
This method returns a list of string arrays, these arrays are retrieved from an SQLite database. Everything works apart from the fact that the string arrays in my result List seem to be getting overwritten every time the while loop repeats itself. The last println always gives me the currentId of the last row retrieved from the database, but if I put a println inside the while loop it returns the appropriate data on each while cycle. I really can't figure out where my String[] elements are getting overwritten. It's probably really obvious but I've spent hours looking online to check if I'm doing the add procedure correctly and still no joy. HELP!
You need to create the rowResult array in the loop. Your list just holds a pointer to the array and you are basically only working with one instance all the time.
in while use rowResult = new String[7]; everytime before initializing.
This is because, arrays are objects in Java, so basically you are changing value of same object again and again.
It's because you are reassigning the array locations:
rowResult[0] = (currentId);
rowResult[1] = (manufacturer);
rowResult[2] = (type);
rowResult[3] = (series);
rowResult[4] = (operator);
rowResult[5] = (baseAirport);
rowResult[6]= (index);
Create a temporary String array inside your while loop and add that to your result:
while (rs.next()) {
String[] rowResult = new String[7];
..
// do your stuff
result.add(rowResult);
}
Every time the while loop executes, it will add it to result and you will start anew.
You are using the same rowResult array for all rows. Put the line
String[] rowResult = new String[7];
inside the while loop, and everything will work fine.
You are overwriting your rowResult object. You have to create a new one, fill it and add it to your list every iteration. What you do is like taking a basket, fill it with oranges and put it on the shelve, then take the same basket, throw the oranges out and put new ones in.
public List<String[]> idOnlyQuery(String searchTerm, Connection conn){
List<String[]> result = new ArrayList<String[]>();
Statement stmt = null;
try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT * FROM Jets WHERE CurrentID LIKE '" + searchTerm + "%'");
while(rs.next()){
String[] rowResult = new String[7];
rowResult[0] = rs.getString("CurrentId");
rowResult[1] = rs.getString("Constructor");
rowResult[2] = rs.getString("ACType");
rowResult[3] = rs.getString("Series");
rowResult[4] = rs.getString("Operator");
rowResult[5] = rs.getString("Home_Airfield");
rowResult[6] = rs.getString("KeyNo");
result.add(rowResult);
}
System.out.println(result.get(0)[0]);
}
catch (Exception e) {}
}
You are overwritting again and again the String array. Try to create a new array in each loop.
List<String[]> result = new ArrayList<String[]>();
String[] rowResult;
Statement stmt = null;
try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT * FROM Jets WHERE CurrentID LIKE '" + searchTerm + "%'");
while(rs.next()){
rowResult = new String[7]; //Create a new object
String currentId= rs.getString("CurrentId");
//...
}
This is because when you are doing this:
rowResult = new String[7]; //Create a new object
This variable points out to an object in memory:
rowResult -------------> new String[7]
So if I do loop over and over the result set and write using rowResult I am indeed only modifying one object (by adding it every time to the list you only have a lot of variables pointing to the same object):
result.get(0) -------------->|
result.get(1)--------------->| String[7]
result.get(n)--------------->|
When creating by new operator an new array in the loop you are indeed having a new fresh object to work with:
result.get(0) -------------->| String[7]
result.get(1)--------------->| String[7]
result.get(n)--------------->| String[7]
I am new in JAVA, so kindly understand my question and please give your valuable and precise answer.
How to store resultset data in anohter array ? Should I use ArrayList etc. My code is just for example.
Statement stmt = null;
ResultSet query_rs;
String query = "SELECT * FROM my_table";
query_rs = stmt.executeQuery(query);
int counter_rs = 0;
ArrayList my_arr = new ArrayList();
while(query_rs.next())
{
//here I want to add one row data in array index
counter_rs++;
my_arr[counter_rs] = query_rs; //Store row data in particular array index
}
System.out.println(my_arr.toString()); //Show all data
P.S. My major line is my_arr[counter_rs] = query_rs;. Thanks in advance
my_arr is arraylist if you want to add any element my_arr.add(anyElement) or if you want to set any element in particular location use this set(int index, E element)
my_arr.set(0,anyElement);
Statement stmt = null;
ResultSet query_rs;
String query = "SELECT * FROM my_table";
query_rs = stmt.executeQuery(query);
int counter_rs = 0;
ArrayList my_arr = new ArrayList();
while(query_rs.next())
{
//here I want to add one row data in array index
my_arr.set(counter_rs,query_rs); //use this
// or
// my_arr.add(query_rs);
counter_rs++;
}
//System.out.println(my_arr.toString()); //Show all data
// use for loop to get all data
my_arr is ArrayList not array
ArrayList my_arr = new ArrayList();
use my_arr.add() not as my_arr[counter_rs] = query_rs;
If i understand your question, then i think you need to do the following:
First declare an arrayList with a RowType like >
ArrayList<DataRow> my_arr = new ArrayList<DataRow>(); // DataRow should hold the columns data.
Second : add each fetched row to the list.
while(query_rs.next())
{
DataRow row = // fill the row from the ResultSet
my_arr.add(row);
}
third : loop over the list and print the data;
this is what i am doing:
String[] output = new String[index.length];
try{
for(int i=0; i<index.length; i++){
Statement st = con.createStatement();
ResultSet res = st.executeQuery(
"SELECT url FROM resources WHERE rid = "+(index[i]);
while(res.next()){
output[i] = res.getString("url"); //<-- this is where exception is thrown
}
} catch(...)
The Method is working but instead of printing the correct url value, it is priting someting like this:
[Ljava.lang.String;#85af80
What does it mean? The url field in mySQL is VarChar, it worked fine with above methods but in this loop why i am getting the above result??
You haven't initialized output[]!
Try this:
String[] output = new String[index.length];
That strange output is caused by printing the array, ie System.out.println(output);
Try this instead:
System.out.println(Arrays.toString(output));
It's kinda lame, but java doesn't automatically print the array contents, it prints the object type and address. The hint is the letter L at the start, which it uses to indicate an array