2012-01-31 18 views
0

假设我有一个表myTable的,如下所示:表的访问 - SQL(Java)的

ID A  B  C 
1 100 APPLE  CAKE 
2 200 BANANA PIE 

我希望能够将所有这些表记录保存到(某种)列表,并通过每个迭代记录。

查询将是:

select * from Mytable where ID in (1,2,3) 

因此,清单应当有2个记录: RECORD1应该包含1100,APPLE,蛋糕 和RECORD2应该包含2,200香蕉,PIE

我也想能够通过记录每个迭代

所以对于RECORD1 - 我想getColumnA即100,getColumnB即APPLE等

+0

看看JDBC:http://docs.oracle.com/javase/tutorial/jdbc/ – 2012-01-31 11:16:29

回答

0
List<YourObject> listOfObjects = new ArrayList<YourObject>(); 
    while(rs.next()){ 
     int id = rs.getInt(1); 
     int A = rs.getInt(2); 
     String B= rs.getString(3); 
     String C = rs.getString(4); 
     YourObject ob = new YourObject (id, A, B, C); 
     listOfObjects.add(ob); //now you have the list of objects .. iterate trough it 
    } 
+0

这里是一个很好的文章。 。简单明了:http://www.devdaily.com/java/java-mysql-select-query-example – tartak 2012-01-31 11:20:27

+0

:谢谢!我认为这会很有用! – user656523 2012-01-31 11:35:25

0

为此,您需要实现JDBC。

创建JDBC连接后。从结果集中执行查询和提取记录。从记录中,您也可以获取特定的列。

看下面的例子how to work with jdbc basic

http://www.jdbc-tutorial.com/

import java.sql.* ; 

class JDBCQuery 
{ 
public static void main(String args[]) 
{ 
    try 
    { 
     // Load the database driver 
     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ; 

     // Get a connection to the database 
     Connection conn = DriverManager.getConnection("jdbc:odbc:Database") ; 

     // Print all warnings 
     for(SQLWarning warn = conn.getWarnings(); warn != null; warn = warn.getNextWarning()) 
     { 
      System.out.println("SQL Warning:") ; 
      System.out.println("State : " + warn.getSQLState() ) ; 
      System.out.println("Message: " + warn.getMessage() ) ; 
      System.out.println("Error : " + warn.getErrorCode()) ; 
     } 

     // Get a statement from the connection 
     Statement stmt = conn.createStatement() ; 

     // Execute the query 
     ResultSet rs = stmt.executeQuery("select * from Mytable where ID in (1,2,3)") ; 

     // Loop through the result set 
     while(rs.next()) 
     { 
     System.out.println(rs.getString('ID')) ; 
     System.out.println(rs.getString('A')) ; 
     System.out.println(rs.getString('B')) ; 
     System.out.println(rs.getString('C')) ; 
     } 

     // Close the result set, statement and the connection 
     rs.close() ; 
     stmt.close() ; 
     conn.close() ; 
    } 
    catch(SQLException se) 
    { 
     System.out.println("SQL Exception:") ; 

     // Loop through the SQL Exceptions 
     while(se != null) 
     { 
      System.out.println("State : " + se.getSQLState() ) ; 
      System.out.println("Message: " + se.getMessage() ) ; 
      System.out.println("Error : " + se.getErrorCode()) ; 

      se = se.getNextException() ; 
     } 
    } 
    catch(Exception e) 
    { 
     System.out.println(e) ; 
    } 
} 
}