0
import java.sql.*;

public class MyClass {
    public Connection LetConnect(){
        Connection conn=null;
        String url,username=null ,password=null;
        url="jdbc:sqlserver://localhost\\SQLExpress;databaseName=Test";
        username="sa";
        password="******"; 

        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            conn=DriverManager.getConnection(url,username,password);
            System.out.println("Connected");
        } catch (SQLException | ClassNotFoundException e){
            e.printStackTrace();
        }
      return conn;
    }

    public static  void FetchData(){
        Connection conn= LetConnect();
        String sql = "select * from employee";
        try {
            Statement st=conn.createStatement();
            ResultSet rs=st.executeQuery(sql);
            while(rs.next()){
                System.out.println(rs.getString(1)+" "+rs.getString(2));
            }
        } catch (SQLException e){
                e.printStackTrace();
        }
    }

    public static void main(String[] args){
        MyClass.LetConnect();
        MyClass.FetchData();
    }
}

I have the code above I keep getting this error error: non-static method LetConnect() cannot be referenced from a static context Connection conn= LetConnect(); not sure what it means

Kaviranga
  • 576
  • 2
  • 10
  • 24
PC55
  • 1
  • 1
  • Does this answer your question? [Non-static variable cannot be referenced from a static context](https://stackoverflow.com/questions/2559527/non-static-variable-cannot-be-referenced-from-a-static-context) – OH GOD SPIDERS Oct 15 '20 at 12:47
  • `LetConnect` isn't static -> it's an "instance method" -> you need to call `myClassInstance.LetConnect()` where `myClassInstance` is an instance of your class (at some point instanciated with `new MyClass`) and can't just call `LetConnect` – Aaron Oct 15 '20 at 13:08

0 Answers0