软件环境: 编译器: IDEA 2019.1 MySQL: 8.0.16 mysql连接驱动:mysql-connect-java-8.0.16 附驱动下载地址: 链接:https://pan.baidu.com/s/1VWYHnVu7TA3-SIqXWNQ4qg 提取码:866b
public class ClassName{ // 根据用户名和密码查询信息 public User MethodName(String uname, String pwd) { // 声明jdbc对象 Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; // 声明对象 User user = null; try { // 加载驱动 Class.forName("com.mysql.cj.jdbc.Driver"); // 创建连接 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo?serverTimezone=GMT+8","root","password"); // 创建sql语句 String sql = "select * from t_user where uname=? and pwd=?"; // 创建命令对象 ps = conn.prepareStatement(sql); // 赋值 ps.setString(1,uname); ps.setString(2,pwd); // 执行sql rs = ps.executeQuery(); // 获取信息 while (rs.next()){ user = new User(); user.setUname(rs.getString("uname")); user.setPwd(rs.getString("pwd")); } return user; // 关闭连接 } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if (rs!=null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (ps!=null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn!=null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } return null; } }