Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// 1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 2.获取连接对象
con = DriverManager.getConnection("jdbc:mysql://ip(or host):port/dbName", "user", "password");
// 3.构建statement对象
String sql = "sql语句";
ps = con.prepareStatement(sql);
// 4.执行sql
rs = ps.executeQuery();
// 5.遍历结果集
while (rs.next()) {
// some business code
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 6.关闭连接
try {
rs.close();
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
PS:
使用PreparedStatement的好处:
1、可读性更好。
2、DB的缓存机制,相同的预编译再次调用不需要重新编译,提高性能。
3、提高了安全性,预编译可以防止sql注入。