1. 加载驱动(连接的是mysql数据库)
Class.forName(“com.mysql.jdbc.Driver”);
2. 建立连接(数据库名称是health,端口号是3306,用户名是root,密码是123456)
Connection conn=
DriverManager.getConnection(jdbc:mysql://localhost:3306/health,
root,123456);
3. 创建sql语句
PreparedStatement ps = conn.prepareStatement(“select * from student where sid=?”);
若有占位符,则需要给占位符赋值
ps.setInt(1,sid);
4. 执行sql语句(查询使用executeQuery,若是修改则是executeUpdate())
ResultSet rs = ps.executeQuery();
5. 执行并操作结果集
Student student=null;
if(rs.next()){
student = new Student(sid,rs.getString(“s_user”),
rs.getString(“s_password”),rs.getString(“s_name”),
rs.getString(“s_sex”),rs.getInt(“s_age”),null);
}
6. 关闭资源
rs.close();
ps.close();
conn.close();