Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
servletResponse.setContentType("text/html;charset=utf-8");
PrintWriter out = servletResponse.getWriter();
try {
String url = "jdbc:mysql://localhost:3306/local?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
String root = "root";
String pwd = "123456";
//加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//获取链接
con = DriverManager.getConnection(url, root, pwd);
//操作数据库
String sql = "select * from user";
ps = con.prepareCall(sql);
rs = ps.executeQuery();
//获取结果集
while (rs.next())
{
String id = rs.getString("id");
String name = rs.getString("name");
out.print(id+","+name+"<br>");
}
} catch (SQLException | ClassNotFoundException throwables) {
throwables.printStackTrace();
}finally {
// 关闭资源
if (rs != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}