//创建一个工具类 public class DbUtil { private static String name; private static String pwd; private static String url; static{ Properties properties=new Properties(); try { properties.load(Thread.currentThread().getContextClassLoader() .getResourceAsStream("sql.properties")); name=properties.getProperty("name"); pwd=properties.getProperty("pwd"); url=properties.getProperty("url"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Connection getConnection(){ Connection conn=null; try { Class.forName("com.mysql.jdbc.Driver"); conn=DriverManager.getConnection(url,name,pwd); } catch (ClassNotFoundException | SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return conn; } public static void closeConn(Connection conn){ if(conn!=null){ try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } //创建配置文件.propertites的配置文件,创建在WEB-INF/classes name:root pwd:admin url:jdbc:mysql://127.0.0.1:3306/j121?useUnicode=true&characterEncoding=UTF-8 public class UserDaoImpl implements UserDAO { @Override public User findUser(String name, String pwd) { //链接数据库 Connection conn=DbUtil.getConnection(); String sql="select * from users where user_name=? and user_pwd=?"; User user=null; try { PreparedStatement ptmt=conn.prepareStatement(sql); ptmt.setString(1, name); ptmt.setString(2, pwd); ResultSet rs= ptmt.executeQuery(); if(rs.next()){ user=new User(); user.setUserId(rs.getInt("user_id")); user.setUserName(rs.getString("user_name")); user.setUserPwd(rs.getString("user_pwd")); user.setUserType(rs.getInt("user_type")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return user; } public static void main(String[] args) { UserDAO userDao=new UserDaoImpl(); System.out.println(userDao.findUser("lisi", "admin")); } }