我使用方法 getTableContent 从db获取一些值并返回String数组。方法如下,
public static String[][] getTableContent(Connection con){
ResultSet rs = null;
Statement st = null;
String [][] data = null;
String sql = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";
try {
st = myConn.createStatement();
rs = st.executeQuery(sql);
if(rs.last()){
data = new String[rs.getRow()][5];
rs.beforeFirst();
}
int count =0;
while ( rs != null && rs.next() ){
data[count][0] =rs.getString(1);
data[count][1] =rs.getString(2);
data[count][2] =rs.getString(3);
data[count][3] =rs.getString(4);
data[count][4] =rs.getString(5);
}
}
catch (SQLException e) {
e.printStackTrace();
}
return data;
}
我在另一个数组中获取表值并尝试打印如下,
String [][] myData = getTableContent(conn);
for ( int i =0; i < myData.length; i++ ){
for ( int j =0; j < myData.length; j++ ){
System.out.print( (myData[j]) + " ");
}
System.out.println();
}
我将以下提供的某些机器值作为样本,
[Ljava.lang.String;@314e4baf [Ljava.lang.String;@4cb71983
我使用myData [j])。toString()但这对我没有帮助。我该如何改进代码?程序中没有错误。
答案 0 :(得分:3)
您的代码中存在错误。耀直接打印1-D数组,打印哈希码而不是实际的数组内容。我在下面纠正了它:
for ( int i =0; i < myData.length; i++ ){
for ( int j =0; j < myData[i].length; j++ ){
// you were printing the 1-D array, which prints hashcode
System.out.print( (myData[i][j]) + " ");
}
System.out.println();
}
或者试试这个:
String [][] myData = getTableContent(conn);
for (int i =0; i < myData.length; i++){
System.out.println( Arrays.toString(myData[i]));
}