查询数据库表,如果用户表sw_user中存在一条username为lisi的数据,则将这条数据的对象返回
使用原始的方法,操作如下:
1、先写一个工具类,有实现MySQL数据库连接的方法,和关闭数据库连接、关闭ResultSet 结果集、关闭PreparedStatement 的方法。代码如下:
package com.swift; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class DBUtil { //连接MySQL数据库工具 public static Connection getConn() { Connection conn=null; try { Class.forName("com.mysql.jdbc.Driver"); try { conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/sw_database?user=root&password=root"); } catch (SQLException e) { e.printStackTrace(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } return conn; } //关闭数据库连接、sql连接、结果集 public static void closeAll(Connection conn,PreparedStatement ps,ResultSet rs) { if(conn!=null) try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } if(ps!=null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if(rs!=null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
使用这个DBUtil来查询数据库表中是否有一条名字为lisi的数据,将这条数据按User对象返回
package com.swift; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class QueryOneObject { public static User queryOneObject() { Connection conn=DBUtil.getConn(); PreparedStatement ps=null; ResultSet rs=null; User user=null; try { ps=conn.prepareStatement("select * from sw_user where username=? and password=?"); ps.setString(1, "lisi"); ps.setString(2, "abcdef"); } catch (SQLException e) { e.printStackTrace(); } try { rs=ps.executeQuery(); } catch (SQLException e) { e.printStackTrace(); } try { while(rs.next()) { String username=rs.getString("username"); String password=rs.getString("password"); user=new User(username,password); } } catch (SQLException e) { e.printStackTrace(); } return user; } }
测试类SeverletDemo
package com.swift; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/demo") public class ServletDemo extends HttpServlet { private static final long serialVersionUID = 1L; public ServletDemo() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().append("Served at: ").append(request.getContextPath()); User user=QueryOneObject.queryOneObject(); response.getWriter().append(user.toString()); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
结果:
下面将用JdbcTemplate的方法完成上面过程: