(1) 注册驱动;
(2) 获取连接对象 Connection;
(3) 创建 prepareStatement对象;
(4) 运行 SQL 语句;
(5) 处理结果;
(6) 关闭连接释放资源。
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection con=null;
PreparedStatement ps=null;
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接
con= DriverManager.getConnection("jdbc:mysql://localhost:3306/day04", "root", "root");
//3.创建预编译对象
ps= con.prepareStatement("select * from user where name = ? ");
//3.5.设置参数
ps.setString(1, "admin");
//4.执行语句
ResultSet rs = ps.executeQuery();
//5.处理结果
while(rs.next()){
System.out.println(rs.getString("name")+":"+rs.getInt("age")+":"+rs.getString("password"));
}
//6.释放资源
try {
if(con!=null){
con.close();
}
if(ps!=null){
ps.close();
}
} catch (Exception e) {
}
}