Java中操作数据库查询数据

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);
}	
}
  1. 接收servlet数据的页面

在这里插入图片描述

代码如下:

<div class="span-style">
	<span>账户:<i>${name}</i></span>
</div>
<div class="span-style">
	<span>密码:<i>${password}</i></span>
</div>

增删查改格式基本都是这样的,唯一不同的就是SQL语句了。

  • 8
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值