1
public C[] getC() throws SQLException, ClassNotFoundException  {
   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
   String url = "jdbc:odbc:Mydb";
   String user = "user1";
   String password = "password";
   Connection con = DriverManager.getConnection(url,user,password);
   Statement smt= con.createStatement();
   String query = "Select ssn, cname from customer";
   ResultSet rs = smt.executeQuery(query);
   C [] c = new C[getNumberOfCustomers()];
   while (rs.next()){
      String ssn = rs.getString("ssn");
      String customer_name = rs.getString("cname");
   }    
   return custarray;    
}

这是C的代码:

public class C {

   private String name;
   private String SocialSecurityNumber;

   public C(String name, String SocialSecurityNumber) {
      this.name = name;
      this.SocialSecurityNumber = SocialSecurityNumber;
   }

   public String getName() { return name; }
   public void setName(String name) { this.name = name; }
   public String getSocialSecurityNumber() { return SocialSecurityNumber; }
   public void setSsn(String SocialSecurityNumber ) {
      this.SocialSecurityNumber = SocialSecurityNumber;
   }
}

在这里,我在将 ssn 和 customer_name 传递给C[]数组时遇到问题

4

2 回答 2

1
C [] c = new C[getNumberOfCustomers()];
int i = 0;
while (rs.next()){
   c[i++] = new C( rs.getString( "cname" ), rs.getString( "ssn" ));
}

仅供参考: AList<C> 会比数组更好C,以下代码使用可重用列表,new仅在target == null(例如第一次使用)时发生。

public List<C> getC( List<C> target ) throws SQLException,ClassNotFoundException{
   if( target == null ) {
      target = new LinkedList<C>();
   }
   else {
      target.clear();
   }
   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
   String url = "jdbc:odbc:Mydb";
   String user = "user1";
   String password = "password";
   Connection con = DriverManager.getConnection(url,user,password);
   Statement smt= con.createStatement();
   String query = "Select ssn, cname from customer";
   ResultSet rs = smt.executeQuery(query);
   while( rs.next()){
      target.add( new C( rs.getString("cname"), rs.getString("ssn")));
   } 
   return target;
}
于 2013-05-14T17:36:04.603 回答
0

你可以这样做:

List<C> list = new ArrayList<C>();
while (rs.next()){
    String ssn = rs.getString("ssn");
    String customer_name = rs.getString("cname");
    C c = new C(ssn, customer_name);
    list.add(c);
}
C[] lc = new C[list.size()];
list.toArray(lc);
于 2013-05-14T17:50:58.953 回答