简体   繁体   中英

Reading data from MySQL into eclipse

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM