Non-static variable cannot be referenced from static variable error when connecting database with java

118 views Asked by At

Hello i'm getting a coding problem in my class for some reason. i'm trying to connect between the database and the netbeans but keep getting the error mentioned above in the title

mainly this is the class getting the error :

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

public class DBHandler extends Configs {

   Connection dbconnection;
   
   public Connection getConnection()
   {
       String connectionString = "jdbc:mysql://"+ Configs.dbhost + ":" + Configs.dbport + "/" + Configs.dbname;
       
       try {
           Class.forName("com.mysql.jdbc.Driver");
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       }
       
         try {
           dbconnection = DriverManager.getConnection(connectionString,Configs.dbuser,Configs.dbpass);
       } catch (SQLException e) {
           e.printStackTrace();
       }
        
       return dbconnection;
       
   }
   
   
}

this is the sub class of Configs ^ which is very simple so far here it is :

public class Configs {
    protected String dbhost  = "a host";
    protected String dbport = "a port";
    protected String dbuser = "a user";
    protected String dbpass = "a password";
    protected String dbname = "a name";
    
}

will add more to configs but after i figure out how to fix the error i'm getting (got the mysql library imported btw)

1

There are 1 answers

0
Vitaliy Yakovchuk On

Use 'this' instead of the 'Configs' in the getConnection method. e.g. 'this.dbhost', etc

The syntax you use for accessing static variables