[英]Table access - SQL (Java)
假設我有一個表MYtable,如下所示:
ID A B C
1 100 APPLE CAKE
2 200 BANANA PIE
我希望能夠將所有這些表記錄保存到列表(某種形式)中並遍歷每個記錄。
查詢將是:
select * from Mytable where ID in (1,2,3)
因此,該列表應具有2條記錄:record1應包含1,100,APPLE,CAKE和record2應包含2,200,BANANA,PIE
我還希望能夠遍歷每條記錄
所以對於record1-我想要getColumnA即100,getColumnB即APPLE,依此類推
首先,您將需要JDBC連接到數據庫。
您可以使用Statement或PreparedStatement從數據庫中獲取數據,然后可以獲取存儲在ResultSet中的數據。
現在,您可以遍歷ResultSet中的結果。
為此,您需要實現JDBC。
創建JDBC連接后。 執行查詢並從結果集中獲取記錄。 從記錄中,您還可以獲取特定的列。
請參見以下示例, 如何使用jdbc basic
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 ) ;
}
}
}
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.