在“尝试使用资源"中使用PreparedStatement显示“未知类"错误 [英] Using PreparedStatement in Try with Resources shows 'unknown class' error

查看:120
本文介绍了在“尝试使用资源"中使用PreparedStatement显示“未知类"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在全局初始化一个准备好的语句(因此它不会在每次运行函数时都进行预编译,只有在加载应用程序时才进行预编译),并尝试在资源中尝试使用prepareed语句,但是它显示了一个未知类别"错误.这是代码:

I am initialising a prepared statement globally (so it isn't pre-compiled everytime a function is run, only when the application is loaded), and attempting to use the preparedstatement in a try with resources, but it is showing an 'unknown class' error. This is the code:

private PreparedStatement ingredientDelete;

public void deleteIngredient(String name) {
    try(ingredientDelete = con.prepareStatement(DELETE_INGREDIENT_BY_NAME)){
        ingredientDelete.setString(1, name);
        ingredientDelete.execute();

    }catch(SQLException e){
        System.out.println("Delete failed - " + e.getMessage());

    }
}

为清楚起见,该连接是在另一个方法中打开的,并且也在全局中声明.

For clarity the connection is opened in another method and also declared globally.

推荐答案

那不是有效的Java.尝试中声明的资源必须是局部变量,因此必须声明其类型.请参见 JLS

That isn't valid Java. The resourced declared in the try must be local variables, and thus have their type declared. See the JLS

Resource:
    VariableModifiersopt Type VariableDeclaratorId = Expression

使该字段无意义,因为一条语句绑定到一个连接,并且由于无论如何每次调用该方法都将重新创建它,因此有可能在多个线程中使用同一条语句.

Making it a field doesn't make sense anyway, since a statement is bound to a connection, and since you're re-creating it every time the method is called anyway, thus potentially using the same statement in multiple threads.

您正在预先优化,这是万恶之源.该数据库已经具有准备好的语句的高速缓存.不需要自己做.而且,您当然也应该使用连接池,而不是对所有程序使用单个连接.

You're pre-optimizing, which is the root of all evil. The database already has a cache of prepared statements. No need to do that by yourself. And you should definitely use a connection pool, too, instead of using a single connection for all your program.

这篇关于在“尝试使用资源"中使用PreparedStatement显示“未知类"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆