Reading data from MySQL into eclipse

85 views Asked by At

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?

3

There are 3 answers

1
Andres On BEST ANSWER

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>();
0
Dave On

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.

0
unknown On

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));
}