Java JDBC檢索表內容
如何使用JDBC連接來檢索一個表的內容是什麼?
解決方法
下麵的示例使用getString,getInt & executeQuery方法來獲取和顯示表的內容。
import java.sql.*; public class jdbcResultSet { public static void main(String[] args) { try { Class.forName("org.apache.derby.jdbc.ClientDriver"); } catch(ClassNotFoundException e) { System.out.println("Class not found "+ e); } try { Connection con = DriverManager.getConnection ("jdbc:derby://localhost:1527/testDb","username", "password"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery ("SELECT * FROM employee"); System.out.println("id name job"); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); String job = rs.getString("job"); System.out.println(id+" "+name+" "+job); } } catch(SQLException e){ System.out.println("SQL exception occured" + e); } } }
結果
上麵的代碼示例將產生以下結果。該結果可能會不同。
id name job 1 alok trainee 2 ravi trainee