Java 请告诉我为什么控件不进入pst.setString(1,用户名);下一行控件直接进入elseif(more=true)第三行
查看进入Java 请告诉我为什么控件不进入pst.setString(1,用户名);下一行控件直接进入elseif(more=true)第三行,java,Java,查看进入else if(more){}块的准备语句后的控件 try{ //System.out.println("iam in first line"); Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection(url,user,passsword); String userName = ex.getUserName(); String pas
else if(more){}
块的准备语句后的控件
try{
//System.out.println("iam in first line");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url,user,passsword);
String userName = ex.getUserName();
String password = ex.getPassword();
PreparedStatement pst = con.prepareStatement("Select * from employee where username = ? and password = ? "); `after this line control is not there`
pst.setString(1, userName);
pst.setString(2, password);
int k = pst.executeUpdate();
boolean more;
if(k > 0)
{
//boolean more = rs.next();
more = true;
}
else {
more = false;
}
if(!more)
{
System.out.println("you are not a registered user!");
ex.setValid(false);
}
else if(more)
{
String firstName = rs.getString("name");
String lastName = rs.getString("rollnumber");
System.out.println("Welcome " + firstName); `control coming here`
ex.setFirstName(firstName);
ex.setLastName(lastName);
ex.setValid(true);
}
}
catch(Exception tex)
{
tex.printStackTrace();
//System.out.println("hey there is an exception " +ex);
}
主要问题是使用
intk=pst.executeUpdate()代码>
您的查询不是update语句,因此执行update是没有意义的,它可能总是返回0
,因为没有更新的行
改为使用executeQuery
,它返回一个ResultSet
,例如,它可以用来确定是否有任何行与您的查询匹配
try{
//System.out.println("iam in first line");
Class.forName("com.mysql.jdbc.Driver");
try (Connection con = DriverManager.getConnection(url,user,passsword)) {
String userName = ex.getUserName();
String password = ex.getPassword();
PreparedStatement pst = con.prepareStatement("Select * from employee where username = ? and password = ? "); `after this line control is not there`
pst.setString(1, userName);
pst.setString(2, password);
try (ResultSet rs = pst.executeQuery()) {
if (rs.hasNext()) {
// Registered
} else {
// Unregistered
}
}
}
}
catch(Exception tex)
{
tex.printStackTrace();
//System.out.println("hey there is an exception " +ex);
}
您可能想更仔细地查看一下我尝试过的executeQuery(),它返回的是resultset,但是y控件没有到达pst.setString(1,userName)PreparedStatement pst=con.prepareStatement(“选择*from employee,其中userName=?和password=?”;pst.setString(1,用户名);pst.setString(2,密码);rs=pst.executeQuery();布尔更多=rs.next();如果(!more){System.out.println(“您不是注册用户!”);ex.setValid(false);}@HimanshuRawat,则不需要这样做。查询将返回一个带行的ResultSet
,或者返回一个空的ResultSet
,因此使用if(rs.hasNext())
;检查与您的MySQL服务器版本对应的手册,以了解在com.MySQL.jdbc.SQLError.createSQLException(SQLError.java:936)com.MySQL.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)com.MySQL.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)的第1行使用的正确语法在com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)上,您的查询有问题。employee
表的列名是否正确?看起来您使用了字符串连接而不是PreparedStatement