Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

non static variable connection can not be referenced from a static context

Options
  • 04-11-2009 6:04pm
    #1
    Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,098 Mod ✭✭✭✭


    Learnng me some java badly...
    The bolded line is the error. I can fix it by just putting Connection connection; above the line but what is the proper way to do this?
    This static vs non static thing always confuses me and I make crappy little workarounds.
    import java.net.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.sql.*;
    import java.util.*;
    import java.io.*;
    import java.net.*;
    
    public class serverapp {
           Connection connection = null;
        public static void main(String[] args) throws IOException {
            String line;
            DataInputStream is =null;
            PrintStream os = null;
            ServerSocket serverSocket = null;
            
    
    
            try {
                serverSocket = new ServerSocket(4444);
            } catch (IOException e) {
                System.err.println("Could not listen on port: 4444.");
                System.exit(1);
            }
    
            Socket clientSocket = null;
    
    
    
             try {
               clientSocket = serverSocket.accept();
               is = new DataInputStream(clientSocket.getInputStream());
               os = new PrintStream(clientSocket.getOutputStream());
    // As long as we receive data, echo that data back to the client.
               while (true) {
                 line = is.readLine();
                 os.println(line);
               }
            }
        catch (IOException e) {
               System.err.println("Could not accept socket.");
                System.exit(1);
                 os.close();
            is.close();
            clientSocket.close();
            serverSocket.close();
            }
            
                    try {
                             Class.forName("com.mysql.jdbc.Driver").newInstance();
           }
       catch (Exception e)
           {
                            System.err.println("Driver Error");
                            System.exit(1);
           }
            try {
    [B]connection = DriverManager.getConnection([/B]
    "jdbc:mysql://localhost/trainsystem?user=root&password=");
    } catch(SQLException e) {
    System.out.println("Unable to connect to database");
    System.exit(1);
    }
    }
    private void displaySQLErrors(SQLException e) {
    System.out.println("SQLException: " + e.getMessage());
    System.out.println("SQLState: " + e.getSQLState());
    System.out.println("Error: " + e.getErrorCode());
    
    
    Vector v = new Vector();
    try {
    Statement statement = connection.createStatement();
    ResultSet rs = statement.executeQuery("SELECT * FROM pet");
    while(rs.next()) {
    v.addElement(rs.getString("name"));
    }
    rs.close();
    } catch(Exception t) {System.err.println("Query Error");
    System.exit(1); }
    }
    
    
    
    
    
        }
    


Comments

  • Registered Users Posts: 68,317 ✭✭✭✭seamus


    Is there any particular reason why
    " Connection connection = null;"
    is declared outside of the main() method?


  • Registered Users Posts: 2,150 ✭✭✭dazberry


    I'm not a Java dev but AFAIKs the connection field is part of the serverapp class, but that class hasn't been instantiated because you're running from the static main() method. You've a few choices here, either make the connection field static, move the connection field into the scope of the main method, or instantiate the serverapp class and reference connection from myserverapp.connection.

    D.


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,098 Mod ✭✭✭✭Tar.Aldarion


    seamus wrote: »
    Is there any particular reason why
    " Connection connection = null;"
    is declared outside of the main() method?
    Whoops, no, I was jsut moving it around the place to see what different errors I get. When I have it declared in main() The
    "Statement statement = connection.createStatement();" line gives an error sayting that it can not find the variable connection so I have to declare it again down there.
    Just wondering what to do, if I declare "Connection connection = null;" as static outside of main I get no errors as suggested below.
    dazberry wrote: »
    I'm not a Java dev but AFAIKs the connection field is part of the serverapp class, but that class hasn't been instantiated because you're running from the static main() method. You've a few choices here, either make the connection field static, move the connection field into the scope of the main method, or instantiate the serverapp class and reference connection from myserverapp.connection.

    D.
    cheers, I am bad with this class stuff, 'reference connection from myserverapp.connection.'

    make a class and call connection is it?
    Ah no wait, like Connection connection = new connection;?


  • Registered Users Posts: 3,766 ✭✭✭Reku


    seamus wrote: »
    Is there any particular reason why
    " Connection connection = null;"
    is declared outside of the main() method?

    I had to use an editor to see the code to clear things up but the last few lines of his/her code are a function outside the main function, and they require access to the connection variable so it needs to either be declared outside the main or passed to the function as an input.
    e.g.
    private void displaySQLErrors(SQLException e, Connection x)
    {
    Connection connection = x;
    etc...
    }

    P.S. don't forget to change the function call in the main to include the connection object.


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,098 Mod ✭✭✭✭Tar.Aldarion


    See, I'm pretty bad at this stuff, didn't know I was making another method outside the main method. That would make sense..thanks.

    P.S. don't forget to change the function call in the main to include the connection object.
    What do you mean? /confused
    I should have used that noob tag...


  • Advertisement
  • Registered Users Posts: 2,150 ✭✭✭dazberry


    cheers, I am bad with this class stuff, 'reference connection from myserverapp.connection.'

    make a class and call connection is it?
    Ah no wait, like Connection connection = new connection;?

    Well what I meant there was that as the connection variable is declared as a field in the serverapp class (in the example), if you instantiated the serverapp class inside you main static method you could reference the field via that instantiated class, e.g.
    public class serverapp {
        public Connection connection = null;
        public static void main(String[] args)
        [snip]
        serverapp myserverapp = new serverapp();
        serverapp.connection = DriverManager.getConnection(...);              
    

    D.


  • Registered Users Posts: 3,766 ✭✭✭Reku


    See, I'm pretty bad at this stuff, didn't know I was making another method outside the main method. That would make sense..thanks.



    What do you mean? /confused
    I should have used that noob tag...
    I meant that if you use that way of allowing the connection to be used in the method at the end when you call the method make sure to call it including the connection as an input.
    Though after looking through the code I can't actually see where you call it in the main function.:confused:


    Are there any other classes in the program or is it just that one?
    I've never used the jdbc.

    At a guess the following would be what you might want;
    import java.net.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.sql.*;
    import java.util.*;
    import java.io.*;
    import java.net.*;
    
    public class serverapp 
    {
           Connection connection = null;
        public static void main(String[] args) throws IOException 
       {
            String line;
            DataInputStream is =null;
            PrintStream os = null;
            ServerSocket serverSocket = null;
            
    
    
            try 
           {
                serverSocket = new ServerSocket(4444);
            } 
            catch (IOException e) 
           {
                System.err.println("Could not listen on port: 4444.");
                System.exit(1);
            }
    
            Socket clientSocket = null;
    
    
    
             try 
            {
               clientSocket = serverSocket.accept();
               is = new DataInputStream(clientSocket.getInputStream());
               os = new PrintStream(clientSocket.getOutputStream());
    // As long as we receive data, echo that data back to the client.
               while (true) 
    	{
                 line = is.readLine();
                 os.println(line);
    	}
            }
            catch (IOException e) 
            {
                 System.err.println("Could not accept socket.");
                 System.exit(1);
    	os.close();
    	is.close();
    	clientSocket.close();
    	serverSocket.close();
            }
            
           try 
           {
    	Class.forName("com.mysql.jdbc.Driver").newInstance();
           }
           catch (Exception e)
          {
    	System.err.println("Driver Error");
    	System.exit(1);
          }
    
            try 
          {
    	connection = DriverManager.getConnection("jdbc:mysql://localhost/trainsystem?user=root&password=");
          } 
           catch(SQLException e) 
          {
    	System.out.println("Unable to connect to database");
                 [B]displaySQLErrors(SQLException e, connection) [/B]
    	System.exit(1);
          }
      }
    
    [B]private void displaySQLErrors(SQLException e, Connection x) [/B]
    {
           [B]Connection connection = x;[/B]
           System.out.println("SQLException: " + e.getMessage());
           System.out.println("SQLState: " + e.getSQLState());
           System.out.println("Error: " + e.getErrorCode());
    
           Vector v = new Vector();
           try 
          {
                 Statement statement = connection.createStatement();
    	ResultSet rs = statement.executeQuery("SELECT * FROM pet");
    	while(rs.next()) 
    	{
    		v.addElement(rs.getString("name"));
    	}
    	rs.close();
           } 
           catch(Exception t)
           {
    	System.err.println("Query Error");
    	System.exit(1); 
           }
       }
    }
    

    I've put the changes in bold.


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,098 Mod ✭✭✭✭Tar.Aldarion


    dazberry wrote: »
    Well what I meant there was that as the connection variable is declared as a field in the serverapp class (in the example), if you instantiated the serverapp class inside you main static method you could reference the field via that instantiated class, e.g.
    public class serverapp {
        public Connection connection = null;
        public static void main(String[] args)
        [snip]
        serverapp myserverapp = new serverapp();
        serverapp.connection = DriverManager.getConnection(...);              
    

    D.

    Ah thanks very much, I prefer to see code as terms just confuse me!

    myserverapp.connection = DriverManager.getConnection(...);
    ;)


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,098 Mod ✭✭✭✭Tar.Aldarion


    farohar wrote: »
    I meant that if you use that way of allowing the connection to be used in the method at the end when you call the method make sure to call it including the connection as an input.
    Though after looking through the code I can't actually see where you call it in the main function.:confused:
    Are there any other classes in the program or is it just that one?
    I've never used the jdbc.

    Ah ok cheers, just getting very confused as of yet trying to code the server and client at the same time.
    Making a train ticket booking system thing.
    Program is just meant to be a GUI connected to a database, retrieves info from database, sends info over sockets to serverapp, serverapp queries other databases, returns info over sockets to client.

    Ah I see your code now, yep, something like it I think!
    That gives me errors but I'll mess about.


  • Registered Users Posts: 569 ✭✭✭none


    OK, here's a brief introduction into the static/instance theory if you want.

    It's all about memory, as with everything computer-related. Every Java program is built from instances of classes which are loaded into memory.

    [PHP]class TheClass {
    String itsme = "This is The Class instance variable";
    }

    class TheProgram {
    public static void main (String args[]){
    TheClass class1 = new TheClass();//New instance
    System.out.println(class1.itsme);//Print instance variable
    }
    }[/PHP]

    The code above show how your program (TheProgram) uses classes (TheClass). The important point here is that the program creates an instance of class TheClass to access its variable. Therefore, the variable (itsme) called instance variable. It lives withing the instance and so you need to instantiate TheClass to access its instance (or just normal, i.e., without static keyword) variables.

    Now consider this change to the above classes.

    [PHP]class TheClass {
    static String itsme = "This is The Class static variable";
    }

    class TheProgram {
    public static void main (String args[]){
    System.out.println(TheClass.itsme);//Print static variable
    }
    }[/PHP]


    The main difference, as you can see, there is no need to instantiate TheClass to access its static variables. Of course, you can create an instance and still be able to access its static variables but that's not the way they are supposed to be used.

    What I'm trying to say here is that when you access static members, you are basically using TheClass class rather than its instances. And as such, in memory there's only one static member per program as opposed to multiplicity of instance variables.

    Why you can't access instance members from static members? Because there's always only one static member of TheClass which lives in its own memory and it has no knowledge of how many TheClass instances (or objects) you may create and where they may live in memory. On the other hand, all those instances created can easily access a static (or class) member because they always know this member is one and only and it lives in a specific place in memory. If you know OO principles, you will easy see an analogy between classes and objects.

    In short, static means it's one and residing in a known place so easy to get, while instance means it's many (you don't know how many) and scattered all over the place so you need some leads (parent class instance) to find them.

    By the way, it the above example main is a static method of TheProgram class and out is a static field of System class.


  • Advertisement
  • Closed Accounts Posts: 404 ✭✭kenbrady


    Ah ok cheers, just getting very confused as of yet trying to code the server and client at the same time.
    Making a train ticket booking system thing.
    Program is just meant to be a GUI connected to a database, retrieves info from database, sends info over sockets to serverapp, serverapp queries other databases, returns info over sockets to client.

    Ah I see your code now, yep, something like it I think!
    That gives me errors but I'll mess about.
    You should practise with more basic programs first to get started
    public class ServerApp {
    
        ServerSocket serverSocket = null;
        Socket clientSocket = null;
        PrintWriter out = null;
        BufferedReader in = null;
        Connection connection = null;
    
        public ServerApp() {
            // create server socket
            try {
                serverSocket = new ServerSocket(4444);
            }
            catch (IOException e) {
                System.err.println("Could not listen on port: 4444.");
                System.exit(1);
            }        
    
            try {
                // it will now wait until a client connects to iy
                clientSocket = serverSocket.accept();
    
                // need to put threads in here to handle multiple clients
    
                // client connected get input and output
                //is = new DataInputStream(clientSocket.getInputStream());
                //os = new PrintStream(clientSocket.getOutputStream());
                out = new PrintWriter(clientSocket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    
                // As long as we receive data, echo that data back to the client.
                // this will just keep doing this forever, you need to put a break clause in it
                String line = null;
                while (!"close".equals(line)) { // this means if client sends close it will close socket
                    line = in.readLine();
                    out.println(line);
                }
    
                // close everything
                out.close();
                in.close();
                clientSocket.close();
                serverSocket.close();
            }
            catch (IOException e) {
                System.err.println("Could not accept socket.");
                System.exit(1);            
            }
    
            // you are doing nothing with this
            try {
                Class.forName("com.mysql.jdbc.Driver").newInstance();
            }
            catch (Exception e) {
                System.err.println("Driver Error");
                System.exit(1);
            }
            try {
                connection = DriverManager.getConnection(
                        "jdbc:mysql://localhost/trainsystem?user=root&password=");
            }
            catch (SQLException e) {
                System.out.println("Unable to connect to database");
                System.exit(1);
            }
        }
    
        public static void main(String[] args) throws IOException {
            ServerApp server = new ServerApp();
        }
    
        private void displaySQLErrors(SQLException e) {
            System.out.println("SQLException: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("Error: " + e.getErrorCode());
    
    
            Vector<String> v = new Vector<String>();// correct way to use vectors, you should use ArrayList instead, unless you need it to be synchronised
            try {
                Statement statement = connection.createStatement();
                ResultSet rs = statement.executeQuery("SELECT * FROM pet");
                while (rs.next()) {
                    v.add(rs.getString("name"));
                }
                rs.close();
            } catch (Exception t) {
                System.err.println("Query Error");
                System.exit(1);
            }
        }
    }
    


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,098 Mod ✭✭✭✭Tar.Aldarion


    Cheers guys! Both very helpful.

    When you say:
    // you are doing nothing with this
            try {
                Class.forName("com.mysql.jdbc.Driver").newInstance();
            }
            catch (Exception e) {
                System.err.println("Driver Error");
                System.exit(1);
            }
            try {
                connection = DriverManager.getConnection(
                        "jdbc:mysql://localhost/trainsystem?user=root&password=");
            }
            catch (SQLException e) {
                System.out.println("Unable to connect to database");
                System.exit(1);
            }
        }
    
    Is it not giving an error unless the driver is found and then again if I can't connect to DB?


  • Closed Accounts Posts: 404 ✭✭kenbrady


    Cheers guys! Both very helpful.

    When you say:
    // you are doing nothing with this
            try {
                Class.forName("com.mysql.jdbc.Driver").newInstance();
            }
            catch (Exception e) {
                System.err.println("Driver Error");
                System.exit(1);
            }
            try {
                connection = DriverManager.getConnection(
                        "jdbc:mysql://localhost/trainsystem?user=root&password=");
            }
            catch (SQLException e) {
                System.out.println("Unable to connect to database");
                System.exit(1);
            }
        }
    
    Is it not giving an error unless the driver is found and then again if I can't connect to DB?
    Re read your original code, it will never reach the above.


Advertisement