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 に答える