1

I am working with student registration and login system using MySQL and java in CLI. I want to retrieve data from the database table by entering the username. Data of the relevant username should come to the CLI in the needed place. This is the code I has written

package lab;
import java.sql.*;
import java.util.Scanner;

public class Student_Login {
    String uname, pwd;
    public void input(){
        System.out.println("Student Login Form\nUsername: ");
        Scanner sc = new Scanner(System.in);
        uname = sc.next();
        System.out.println("Password: ");
        pwd = sc.next();
    }
    public void retrieve(){

        try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/mydatabase", "root", "Luxan@22"
            );
            Statement st = con.createStatement();
            ResultSet result =  st.executeQuery("select * from emp where Username = "+uname);
            result.next();
            String Name = result.getString(2);
            System.out.println("Hi "+Name+"You have successfully registered for the following courses");
            ResultSet rs = st.executeQuery("select * from course where username ="+ uname);
            result.next();
            String course = rs.getString(2);
            System.out.println(course);
            con.close();
        }catch(Exception e) {System.out.println(e);}
    }
    public void choice() {
        System.out.println("Please select an option\n1.Exit\n2.Registration");
        Scanner sc = new Scanner(System.in);
        int select = sc.nextInt();
        switch(select) {
        case 1:
            System.out.println("Bye");
            break;
        case 2:
            Student_Registration SR = new Student_Registration();
            SR.input();
            SR.add();
            SR.Display();
            break;
        }
    }

}

But when running the code an exception is coming like below. I entered the user name luxan which is already stored in the table:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'luxan' in 'where clause'

1 Answers1

1

Use a prepared statement:

String sql = "SELECT * FROM emp WHERE Username = ?";
PreparedStatement st = con.prepareStatement(sql);
st.setString(1, uname);
ResultSet rs = st.executeQuery();
if (rs.next()) {
    String Name = result.getString(2);
}

I didn't make an effort to refactor your entire code, but the basic idea behind prepared statements is that variable parameters are simply represented by a ? placeholder, to which we bind values from Java.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360