【问题标题】:The value of the local variable conn is not used未使用局部变量 conn 的值
【发布时间】:2018-10-06 13:18:56
【问题描述】:

正如我在该主题中提到的,我正面临“未使用局部变量 conn 的值”的警告

我清楚地在我的编码中使用了该变量,但它向我显示了这种类型的错误。 如果您能就此提出建议,我们将不胜感激。

[代码]

package jdbc;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

public class example {
    public static void main(String[] ar) {


        try {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("Success to find Driver");
        }catch(ClassNotFoundException e) {
            System.err.println("error = Failed to find driver");
        }//*Find MYSQL driver

        Connection conn = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/class", "root", "****");
            System.out.println("Connected to MySql");
        } catch (SQLException e) {
            System.err.println("error = Failed to Create connection");
        }//* Creating Connection

        }
    }

[运行后的结果]

成功找到驱动程序 错误 = 无法创建连接

【问题讨论】:

  • 好吧,你定义了 conn 但你从来没有对它做任何事情。您期望会发生什么?

标签: java mysql connection


【解决方案1】:

在您的代码中,您已经分配了对 conn 的引用,但您没有在任何地方使用该对象,因此发出 警告

要消除警告,请在某处使用它(也许在某处使用sysout)或添加@SuppressWarnings("unused") 注释

【讨论】:

  • 感谢您的回复。但是连接 conn = null;尝试 { conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/class", "root", "****");我在这里使用 conn 这是错误的使用方式吗?
  • 没有错。即使您使用Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/class", "root", "****");,您也会收到相同的警告,因为在任何一种情况下,您都没有在分配后使用对象conn
  • 再次感谢您的及时回复。正如您所看到的代码,我正在尝试使用正确的凭据建立连接,但它一直失败。你对此有什么想法吗?
  • 异常信息中会有线索。打印堆栈跟踪。
  • 尝试:System.err.println("error = Failed to Create connection" + e); 获取异常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-17
  • 2011-05-05
  • 1970-01-01
相关资源
最近更新 更多