gpt4 book ai didi

java - MySQL、Java – 错误

转载 作者:太空宇宙 更新时间:2023-11-03 11:50:02 25 4
gpt4 key购买 nike

我创建了发送命令“SELECT * FROM cars;”的方法到我的MySQL数据库。 “汽车”是我的表,我想向用户显示数据库的内容,但是当我尝试调用该方法时它会给我输入一些错误。

主要代码:

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);
}
}

}

执行代码:

public void showCars (Cars cars){
sql = "SELECT * FROM cars;";
}

错误信息:

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)

最佳答案

引用Javadoc of executeUpdate() :

Executes the SQL statement in this PreparedStatement object, which must be an SQL Data Manipulation Language (DML) statement, such as INSERT, UPDATE or DELETE

您的查询是 SELECT,因此这将失败。正如错误信息所说:

Can not issue executeUpdate() for SELECTs

调用executeQuery()相反。

关于java - MySQL、Java – 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36024248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com