I created method that will send command "SELECT * FROM cars;" to my MySQL database. The "cars" is my table and I want to show contents of database to user, but it types me some error when I tried to call the method.
main code:
public class main {
public static void main(String[] args) {
String dbHost="localhost";
String dbDatabase="cars";
String dbUser = "root";
String dbPassword = "";
int Select;
Scanner input = new Scanner(System.in);
Cars cars = new Cars();
CarDAO carDAO = new CarDAO();
System.out.println("Choose option: ");
System.out.println("1. Create a new car");
System.out.println("2. Update entry of the car");
System.out.println("3. Sold car");
System.out.println("4. View all cars that are for sale ");
System.out.println("5. Search for cars");
Select = input.nextInt();
switch (Select){
case 1: {
carDAO.createCar(cars);
break;
}
case 2:{
carDAO.changeEntry(cars);
break;
}
case 3:{
carDAO.soldCar(cars);
break;
}
case 4:{
carDAO.showCars(cars);
break;
}
case 5:{
carDAO.search(cars);
break;
}
}
try {
// register driver
Class.forName("com.mysql.jdbc.Driver");
// Make Connection Url
String connectionUrl = "jdbc:mysql://" + dbHost
+ "/" + dbDatabase
+ "?user=" + dbUser
+ "&password=" + dbPassword;
//open Connection
Connection conn = DriverManager.getConnection(connectionUrl);
// Code to create sql and run it will go here
// create SQL
String sql = carDAO.sql;
// prepare Statement
PreparedStatement ps = conn.prepareStatement(sql);
// execute SQL
ps.executeUpdate();
// close connection
conn.close();
}catch (ClassNotFoundException cnfe){
throw new RuntimeException(cnfe);
}catch (SQLException sqle) {
throw new RuntimeException(sqle);
}
}
}
execute code:
public void showCars (Cars cars){
sql = "SELECT * FROM cars;";
}
error message:
Exception in thread "main" java.lang.RuntimeException: java.sql.SQLException: Can not issue executeUpdate() for SELECTs
at main.main(main.java:82)
Caused by: java.sql.SQLException: Can not issue executeUpdate() for SELECTs
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:974)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2416)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2375)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2359)
at main.main(main.java:75)
executeQuery()instead ofexecuteUpdate()?