首页 > 编程知识 正文

Java操作数据库,java 数据库查询

时间:2023-05-04 07:14:09 阅读:219737 作者:356

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 blocke.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 blocke.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语句了。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。