1.确定连接的数据库的类型
2.下载数据库的驱动,把jar包放到WebRoot中WEB-INF下lib里
3.Build Path
4.声明对象
5.加载驱动
6.获取连接
7.创建sql
8.创建sql命令对象
9.给占位符赋值
10.执行sql
11.遍历结果
12.关闭资源
//声明jdbc对象
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
//声明变量
User u=null;
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接
con= DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名", "root", "password");
System.out.println("数据库连接成功:");
//创建sql语句
String sql="select * from t_user where uname=? and pwd=?";
//创建sql命令对象
ps=con.prepareStatement(sql);
//给占位符赋值
ps.setString(1, uname);
ps.setString(2, pwd);
//执行sql
rs=ps.executeQuery();
System.out.println("执行sql成功:");
//遍历结果
if(rs.next()){
//System.out.println("遍历结果:");
//给变量赋值
u=new User();
u.setUid(rs.getInt("uid"));
u.setUname(rs.getString("uname"));
u.setPwd(rs.getString("pwd"));
u.setSex(rs.getString("sex"));
u.setAge(rs.getInt("age"));
u.setBirth(rs.getString("birth"));
}
} catch (Exception e) {
// TODO: handle exception
}//关闭资源
finally{
try {
if(rs!=null)
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(ps!=null)
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(con!=null)
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}