How can I create string and then put the String into preparedStatement, or is this same as using Statement ? When I execute the below code, I've got the following message: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1".
import java.sql.*;
import java.util.Scanner;
class firstApp2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter first name: ");
String firstName = scan.nextLine();
System.out.println(firstName);
firstApp2 test = new firstApp2();
test.selectByFirstName(firstName);
}
public void selectByFirstName(String fn) {
//System.out.println("test");
try {
String dbUrl="jdbc:mysql://localhost:3306/student";
String username="root";
String password="root0216";
//get a connection (step1)
Connection myConnection=DriverManager.getConnection(dbUrl, username, password);
String sql = "Select * from students where firstName = ?";
//create a statement object(step2)
PreparedStatement preparedStatement=myConnection.prepareStatement(sql);
preparedStatement.setString(1, fn);
//execute Query (step 3)
ResultSet myResultSet=preparedStatement.executeQuery(sql);
//process the resultset
while(myResultSet.next()) {
System.out.println("Student full name :" + myResultSet.getString("firstname") +" "+myResultSet.getString("lastname"));
}
}catch(Exception e) {
System.out.println(e.getMessage());
}
}
}