Java操作数据库查询数据的大概流程:
1)创建数据库连接(这里用的是MySQL数据库)
private static String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test"; //数据源(mysql)的连接地址
String user = "root"; //用户名
String password = "root"; //用户密码
static{
try {
//加载驱动
Class.forName(driver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException{
return DriverManager.getConnection(url, user, password);
}
//关闭资源
public static void close(Connection con,PreparedStatement ps,ResultSet rs){
try {
if(con !=null){
con.close();
}
if(ps !=null){
ps.close();
}
if(rs !=null){
rs.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
2)在servlet中查询出数据然后传到页面中(在查询前先设置一下编码格式)
public void insertServlet (HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
//设置请求编码格式
request.setCharacterEncoding("utf-8");
//设置响应编码格式
response.setContentType("text/json;charset=utf-8");
//定义SQL语句,页面获取那些数据就声明修改那些字段
String selectSQL = "select * from asset where UserID = ?";
try {
//获取一开始就创建好的数据库连接
Connection con = ConnectionDatabaseUtil.getConnection();
//创建一个 PreparedStatement 对象来将参数化的 SQL 语句发送到数据库。
PreparedStatement ps = con.prepareStatement(selectSQL);
//给占位符赋值
ps.setString(1, 1);
//执行SQL语句
ps.executeUpdate()
String name = null;
String password = null;
ResultSet rs = ps.executeQuery();
while(rs.next()){
name = rs.getInt("UserName");
password = rs.getInt("UserPassword");
}
request.setAttribute("name", name);
request.setAttribute("password", password);
request.getRequestDispatcher("这里接收数据的页面路径").forward(request, response);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//关闭资源
ConnectionDatabaseUtil.close(con, ps, rs);
}
}
- 接收servlet数据的页面
代码如下:
<div class="span-style">
<span>账户:<i>${name}</i></span>
</div>
<div class="span-style">
<span>密码:<i>${password}</i></span>
</div>
增删查改格式基本都是这样的,唯一不同的就是SQL语句了。