public ArrayList<String []> getTableDataStr(String DBName, String tableName)
throws Exception {
// 连接的不是同一个数据库的话,则要重新连接
if (!url.equals("/" + DBName + "?")) {
conn = this.getConn(DBName);
}
Statement stat = null;
DatabaseMetaData dbmd = null;
ResultSet dbrs = null;
ResultSet rs = null;
ResultSetMetaData rsmd = null;
ArrayList<String[]> result = new  ArrayList<String[]> ();
PreparedStatement ps = conn.prepareStatement("select * from " + tableName);
rs = ps.executeQuery();
rsmd = rs.getMetaData();
//保存一个元素的所有数据
String [] temp = new String[rsmd.getColumnCount()];
while(rs.next()){
for(int j = 1;j<=rsmd.getColumnCount();j++){
temp[j-1] = rs.getString(j);

}

result.add(temp);
}

for(int i = 0;i<result.size();i++){
String [] a = result.get(i);
for(int j = 0 ;j<a.length;j++){
System.out.println(a[j]); //这里老是输出相同的数据。
}
}
return result;
}程序中注释的地方老是输出一想的数据,那个数据是最后一个String[]里的数据,好像前面的String [] 的数据都被覆盖了。。我试了很久还是找不出原因,麻烦大家帮帮我。

解决方案 »

  1.   

    当然老是输出相同的数据了啊,你要在while(rs.next()){这个循环中创建String [] temp = new String[rsmd.getColumnCount()]; 并且在循环中执行这句result.add(temp);添加才行啊 。
      

  2.   


    public ArrayList<String []> getTableDataStr(String DBName, String tableName)
    throws Exception {
    // 连接的不是同一个数据库的话,则要重新连接
    if (!url.equals("/" + DBName + "?")) {
    conn = this.getConn(DBName);
    }
    Statement stat = null;
    DatabaseMetaData dbmd = null;
    ResultSet dbrs = null;
    ResultSet rs = null;
    ResultSetMetaData rsmd = null;
    ArrayList<String[]> result = new ArrayList<String[]> ();
    PreparedStatement ps = conn.prepareStatement("select * from " + tableName);
    rs = ps.executeQuery();
    rsmd = rs.getMetaData();
    //保存一个元素的所有数据while(rs.next()){
    String [] temp = new String[rsmd.getColumnCount()];
    for(int j = 1;j<=rsmd.getColumnCount();j++){
    temp[j-1] = rs.getString(j);
    result.add(temp);
    }
    }for(int i = 0;i<result.size();i++){
    String [] a = result.get(i);
    for(int j = 0 ;j<a.length;j++){
    System.out.println(a[j]); //这里老是输出相同的数据。
    }
    }
    return result;
    }
      

  3.   

    基本楼上就是正解了,还有点小细节问题,就是不知道你这么用PreparedStatement和Statement有什么不同,除了sql参数传入位置不同这点
      

  4.   


    PreparedStatement是先编译的,也就是说一般情况下,如果你的类似sql重复执行多次PreparedStatement效率要高一些,而且PreparedStatement也相对安全,Statement容易被sql注入
      

  5.   

    当然老是输出相同的数据了啊,你要在while(rs.next()){这个循环中创建String [] temp = new String[rsmd.getColumnCount()]; 并且在循环中执行这句result.add(temp);添加才行啊 。