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;
}
}
}
但是在运行代码时,将出现如下异常。我输入了已经存储在表中的用户名luxan:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'luxan' in 'where clause'
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);
}
我没有努力重构整个代码,但是准备好的语句背后的基本思想是,变量参数仅由?
占位符表示,我们将Java的值绑定到该占位符。