Reputation: 149
hello i am working on java and MySQL. My implementation are as follows :
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));
}
}
}
but this code is not working. Giving some sort of exception error but when i remove the line containing if statement then it work fine.How do i check whether the pin is valid or not.
it giving following exception:
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)
Upvotes: 0
Views: 8731
Reputation: 1
if((rs.getString(1)).equals("")){
System.out.println("Invalid PIN");
}
without rs.next()
, rs.getString(1)
is not possible
Try this:
if(rs.next()){
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "+rs.getString(4));
} else {
System.out.println("Invalid PIN");
}
Upvotes: 0
Reputation: 8946
try this way
Replace this Statement st = con.createStatement();
with
String query ="select * from customerinformation where pin =?"
PreparedStatement st =con.prepareStatement("query");
st.setInt(1,PIN);
ResultSet resultSet = st.executeQuery();
You should never use 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());
}
Upvotes: 2