public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/newdb3", "root", "");
String sql = "select * from t_user where uname=? and pwd=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, "张三");
ps.setString(2, "123");
Resultset rs = ps.executeQuery();
System.out.println(rs);
while (rs.next()) {
User u = new User();
u.setUid(rs.getInt("uid"));
u.setUanme(rs.getString("uname"));
u.setPwd(rs.getString("pwd"));
}
System.out.println(u);
rs.close();
ps.close();
conn.close();
}
输入结果U为null,无法进入循环,给u赋值
User u = new User(); 放在while定义了,那么System.out.println(u); 的输出也应该放在while中
while (rs.next()) {
User u = new User();
u.setUid(rs.getInt("uid"));
u.setUanme(rs.getString("uname"));
u.setPwd(rs.getString("pwd"));
System.out.println(u);
}
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/newdb3", "root", "");
while (rs.next()) {
User u = new User();
u.setUid(rs.getInt("uid"));
u.setUanme(rs.getString("uname"));
u.setPwd(rs.getString("pwd"));
}
System.out.println(u);
}
1、数据连接是不是真没有密码
2、局部变量只能在局部使用,所以将对象输出移到while循环里面看是否有输出,如果没有哪么错误点在连接到结果集之间