1

I'm trying to input my details in MySQL using Java. But I keep on having following error:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?, ?)' at line 1

Here is my code:

Vehicle vehicle = new Vehicle();
int vType;
System.out.println("Please enter Vehicle Type\n1 = Car\n2 = Van\n3 = Motorbike\n4 = Motorbike");
vType = input.nextInt();
if (vType==1){
    System.out.println("Car Brand: ");
    vehicle.setvBrand(input.next());
    System.out.println("Car License Plate: ");
    vehicle.setvLicense(input.next());
    try {
        Connection dbConn = DriverManager.getConnection(url,user,pass);
        String parkCar = "INSERT INTO car_park_details(vehicle_brand, vehicle_license) values( ?, ?)";
        PreparedStatement park = dbConn.prepareStatement(parkCar);
        park.executeUpdate(parkCar);
        park.setString(2,vehicle.getvBrand());
        park.setString(3, vehicle.getvLicense());
        park.execute();
        System.out.println("Try daw check sa DB MYONG!");
    }
    catch (Exception ex){
        System.out.println("Error" + ex);
    }
}

Am I doing it wrong? I'm a begginer Java Developer. thanks for the help.

3
  • 1
    You are attempting to execute the query twice, with different methods, and one of the execution is called before query parameters are set. Just remove this line from your code: park.executeUpdate(parkCar); Commented Nov 28, 2019 at 8:26
  • @GMB Not correct. Call park.executeUpdate() with no parameters, and then delete the park.execute() line below it. Commented Nov 28, 2019 at 8:31
  • 1
    @GMB you’re right, just to add, preparedStatement.set starts from index 1. So update that also. Commented Nov 28, 2019 at 9:09

2 Answers 2

1
PreparedStatement park =       dbConn.prepareStatement(parkCar);   
park.setString(1, vehicle.getvBrand());
park.setString(2, vehicle.getvLicense());
park.executeUpdate();

PreparedStatement set parameters index starts from 1.

Sign up to request clarification or add additional context in comments.

Comments

0

Try as below, i.e run executeUpdate() without parameters and only after you have set your parameters to the PreparedStatement:

PreparedStatement park = dbConn.prepareStatement(parkCar);   
park.setString(1,vehicle.getvBrand());
park.setString(2, vehicle.getvLicense());
park.executeUpdate();

1 Comment

The parameter indexes are incorrect here - they should be 1 and 2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.