
public void func3() throws Exception {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 得到连接
String driverClassName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/student";
String username = "root";
String password = "123";
Class.forName(driverClassName);
con = DriverManager.getConnection(url, username, password);// 实例化
// 创建Statement
stmt = con.createStatement();
String sql = "SELECT * FROM emp";
rs = stmt.executeQuery(sql);
// 循环遍历rs,打印其中数据
// getString()和getObject()是通用的!
while (rs.next()) {
System.out.println(rs.getObject(1) + "," + rs.getString("name") + "," + rs.getInt("age")+","+rs.getString("gender"));
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
// 关闭
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
if (con != null)
con.close();
}
}