| //////////////////////////////////////////////////////////// //Get products from the database as a String array //////////////////////////////////////////////////////////// public String[] getProducts() { String[] arr = new String[0]; Connection con; Statement stmt; ResultSet rs; int count = 0; String sql = "select * from p_products order by productID"; try { //Load Driver: Class.forName(driver); //Connect to the database with the url con = DriverManager.getConnection(dburl , dbuid , dbpwd); stmt = con.createStatement(); //Get ResultSet rs = stmt.executeQuery(sql); //Count the records while(rs.next()) {count++;} //Create an array of the correct size arr = new String[count]; //Get ResultSet (the portable way of using rs a second time) rs = stmt.executeQuery(sql); while(rs.next()) { arr[rs.getInt("productID")] = rs.getString("productname"); } stmt.close(); con.close(); } catch (java.lang.Exception ex) { arr[0] = ex.toString(); } return arr; } |
| arr[rs.getInt("productID")] = rs.getString("productname"); |
一些数据库管理系统在缺省情况下就允许数据的自动累加或者自动排序。当你在设计数据库时,一定先查明你的数据库管理系统遵循哪些规则,比如自动累加,自动排序等。