标题:Before start of result set
一、若没有写:resultSet.next();
直接resultSet.getInt(1)
就会报错
二、解决方案,在
ResultSet resultSet = statement.executeQuery(sql);
后面加上resultSet.next();
即可
三、另外注意:
String sql="select count(*) from admin where username='"+username+"' and password='"+pword+"'";
要加‘’单引号,不然就会有Unknown column 'XXX' in 'where clause'
完整代码如下,不过此处有配置文件哦。
public class TestDemoPreparedStatement {
public static void testStatement() throws Exception{
Scanner scanner=new Scanner(System.in);
System.out.print("请输入账号:");
String username=scanner.nextLine();
System.out.print("请输入密码:");
String pword=scanner.nextLine();
//创建Propertise对象
Properties info = new Properties();
//加载jdbc.properties文件
info.load(new FileInputStream("E:/eclipse/Pro01-JDBC02/src/jdbc/jdbc.properties"));
String driver=info.getProperty("driver");
String url=info.getProperty("url");
String user=info.getProperty("user");
String password=info.getProperty("password");
//1.加载厂商驱动
Class.forName(driver);
//2.用java的类获取连接
Connection connection=DriverManager.getConnection(url,user,password);
System.out.println("连接成功");
//3.执行sql语句
//3.1编写sql语句
String sql="select count(*) from admin where username='"+username+"' and password='"+pword+"'";
//3.2创建执行sql的对象
Statement statement = connection.createStatement();
//3.3执行
ResultSet resultSet = statement.executeQuery(sql);
resultSet.next();//Before start of result set
System.out.println(resultSet.getInt(1)>0? "success":"failure");
//4.关闭
resultSet.close();
statement.close();
connection.close();
}
public static void main(String[] args) throws Exception {
TestDemoPreparedStatement.testStatement();
}
}