你好我正在研究java和MySQL。我的实现如下:
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.sql.*;
import java.util.Scanner;
public class BankingSystem extends JFrame {
public static void main(String[] args) throws Exception{
int ur=0;
int PIN;
String ID;
Scanner s=new Scanner(System.in);
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/BankingSystem";
String user = "root";
String pass="";
Connection con = DriverManager.getConnection(url,user,pass);
Statement st = con.createStatement();
System.out.println("Enter Your 4 digit PIN");
PIN=s.nextInt();
ResultSet rs=st.executeQuery("select * from customerinformation where pin ="+PIN);
//checking for existance of user entered pin
if((rs.getString(1)).equals("")){System.out.println("Invalid PIN");}
while(rs.next())
{
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "+rs.getString(4));
}
}
}
但此代码无效。给出某种异常错误,但当我删除包含if语句的行时,它工作正常。如何检查引脚是否有效。
它给出以下例外:
Exception in thread "main" java.sql.SQLException: Before start of result set
at com.mysql.jdbc.ResultSet.checkRowPos(ResultSet.java:3624)
at com.mysql.jdbc.ResultSet.getString(ResultSet.java:1762)
at BankingSystem.main(BankingSystem.java:22)
答案 0 :(得分:2)
试试这种方式
替换此Statement st = con.createStatement();
与
String query ="select * from customerinformation where pin =?"
PreparedStatement st =con.prepareStatement("query");
st.setInt(1,PIN);
ResultSet resultSet = st.executeQuery();
你永远不应该使用Statement over PreparedStatement
if (!resultSet.next() ) {
System.out.println("resultset does not data");
} else {
do {
System.out.println(rs.getString(1)+" "+
rs.getString(2)+" "+
rs.getString(3)+" "+
rs.getString(4));
} while (resultSet.next());
}
答案 1 :(得分:0)
if((rs.getString(1)).equals("")){
System.out.println("Invalid PIN");
}
没有rs.next()
,rs.getString(1)
是不可能的
试试这个:
if(rs.next()){
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "+rs.getString(4));
} else {
System.out.println("Invalid PIN");
}