如何显示表的内容?(How to display contents of table ?)
优质
小牛编辑
124浏览
2023-12-01
问题描述 (Problem Description)
如何使用JDBC连接检索表的内容?
解决方案 (Solution)
下面的示例使用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);
}
}
}
结果 (Result)
上面的代码示例将产生以下结果。 结果可能会有所不同。
id name job
1 alok trainee
2 ravi trainee