简体   繁体   English

java ResultSet和语句问题

[英]java ResultSet and statement issue

i don't understand why my variable state cannot be resolved. 我不明白为什么我的变量状态无法解析。

i'm in a java Mysql project. 我在一个Java Mysql项目中。

Here is the Commands class code: 这是Commands类代码:

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;


public class Commands {

    public Commands() throws SQLException{
        Connection conn = DbConn.getInstance();
        Statement state = conn.createStatement();
    }

    public String getList(){
        System.out.println("Here is a List of our Products:");
        // Get list from db
        ResultSet result = state.executeQuery("SELECT * FROM products");
        ResultSetMetaData resultMeta = result.getMetaData();
        // Display the List

        System.out.println("List displayed");
        return null;
    }
}

Here is the DbConn class code: 这是DbConn类代码:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;


public class DbConn {
      private static String url = "jdbc:mysql://localhost:3306/myDB";
      private static String user = "root";
      private static String passwd = "";
      private static Connection connect;

      // create new instance if not exists
       public static Connection getInstance(){
           if(connect == null){
                try {
                    connect = DriverManager.getConnection(url, user, passwd);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
           }      
           return connect;  
      }   
}

My code is not finished yet, but the message come on this line: 我的代码尚未完成,但是消息出现在这一行:

ResultSet result = state.executeQuery("SELECT * FROM products");

My Eclipse editor says this message state cannot be resolved 我的Eclipse编辑器说此消息状态无法解决

Any idea? 任何想法?

That is a matter of scope. 这是范围问题。 You define the variable here 您在此处定义变量

public Commands() throws SQLException{
    Connection conn = DbConn.getInstance();
    Statement state = conn.createStatement();
}

And that is the only place the variable is visible - in the constructor. 那是变量可见的唯一位置-在构造函数中。 Define it in the class and initialize it in the constructor: 在类中定义它,并在构造函数中对其进行初始化:

private Connection conn = null;
private Statement state = null;

public Commands() throws SQLException{
    conn = DbConn.getInstance();
    state = conn.createStatement();
}

Declare "State" outside of that constructor. 在该构造函数之外声明“状态”。

Connection conn = null;
Statement state = null;

public Commands() throws SQLException{
    conn = DbConn.getInstance();
    state = conn.createStatement();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM