Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 24
  1. #1
    Senior Coder angst's Avatar
    Join Date
    Apr 2004
    Location
    Toronto, Ontario
    Posts
    2,114
    Thanks
    15
    Thanked 122 Times in 122 Posts

    Question mysql connection object?

    hello,

    i'm new to java so please bare with me.

    I've created a mysql class to connect to my server, this part works. however now what I would like to do is be able to initialize that class/object from with in other classes to use the connection.

    my connection class:

    Code:
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.Statement;
    
    public class Connect
    {
    	public static Object conn;
    	
        public static void main (String[] args)
        {
            Connection conn = null;
    
            try
            {
                Class.forName ("com.mysql.jdbc.Driver").newInstance ();
                conn = DriverManager.getConnection ("jdbc:mysql://172.25.0.3:3306/dev", "dev", "dev");
                System.out.println ("Database connection established");
            }
            catch (Exception e)
            {
                System.err.println ("Cannot connect to database server");
                //e.printStackTrace();
                //System.out.println("Exception: " + e.getMessage());
            }
            finally
            {
                if (conn != null)
                {
                    try
                    {
                        conn.close ();
                    }
                    catch (Exception e) { /* ignore close errors */ }
                }
            }
        }
    
    	public Statement createStatement() {
    		// TODO Auto-generated method stub
    		return null;
    	}
    }

    and my select/sql test class

    Code:
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class SqlMethods{
    
    	public static void Select() throws SQLException{
    		
    		Connect conn = new Connect();
            Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery("select * from Admin WHERE AdminID = 3");
            while(rs.next())
            {
            	System.out.println(rs.getString("Username"));
            }
    	}
    }

    any ideas would be great!

    thanks,
    -Ken
    Last edited by angst; 11-11-2010 at 04:08 PM.

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    Hey Angst,
    What you need to do is drop the main method from the connection, and reuse the code in the constructor for the class instead:
    PHP Code:
    private Connection conn;

    public 
    Connect()
            
    conn null;

            try
            {
                Class.
    forName ("com.mysql.jdbc.Driver").newInstance ();
                
    conn DriverManager.getConnection ("jdbc:mysql://172.25.0.3:3306/dev""dev""dev");
                
    System.out.println ("Database connection established");
            }
            catch (
    Exception e)
            {
                
    System.err.println ("Cannot connect to database server");
                
    //e.printStackTrace();
                //System.out.println("Exception: " + e.getMessage());
            
    }
            
    finally
            
    {
                if (
    conn != null)
                {
                    try
                    {
                        
    conn.close ();
                    }
                    catch (
    Exception e) { /* ignore close errors */ }
                }
            }

    Note the change in the conn variable, its been removed from the constructor and replaces the member with typeof Connection instead of Object. Also note that it is no longer static. Then you use with (edit: nvm, its the same as you used in SQLMethods class :P).

    If you want to create many Connect that refer to the same object, you use a private constructor and implement a singleton to use. The only thing that really changes is instead of new Connect(); you would have something like Connect.getInstance();.

    There are things you may want to consider changing, but a lot depends solely on the use. You could add a constructor that takes the location, username and password, you could chain constructors for partials and default data, and you could alter your class to be throwable with the throws SQLException as a part of the constructor signature if you wanted to force the classes using it to handle the errors. The throws seems the most useful to me, as you can catch the errors in the call and determine if or how you want to show it to the user (a cli program would us a System.err.println, and a gui would likely use the JOptionPane.showMessageDialog) without locking it to one or the other.
    Last edited by Fou-Lu; 11-11-2010 at 04:40 PM.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)

  • #3
    Senior Coder angst's Avatar
    Join Date
    Apr 2004
    Location
    Toronto, Ontario
    Posts
    2,114
    Thanks
    15
    Thanked 122 Times in 122 Posts
    ok, I've updated Connect class:

    Code:
    package Lib;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    
    public class Connect
    {
    	private Connection conn;
    
    	public Connect(){
    	        conn = null;
    
    	        try
    	        {
    	            Class.forName ("com.mysql.jdbc.Driver").newInstance ();
    	            conn = DriverManager.getConnection ("jdbc:mysql://172.25.0.3:3306/dev", "dev", "dev");
    	            System.out.println ("Database connection established");
    	        }
    	        catch (Exception e)
    	        {
    	            System.err.println ("Cannot connect to database server");
    	            //e.printStackTrace();
    	            //System.out.println("Exception: " + e.getMessage());
    	        }
    	        finally
    	        {
    	            if (conn != null)
    	            {
    	                try
    	                {
    	                    conn.close ();
    	                }
    	                catch (Exception e) { /* ignore close errors */ }
    	            }
    	        }
    	} 
    
    }
    however I'm getting an error in the SqlMethods class:

    Code:
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class SqlMethods{
    
    	public SqlMethods() throws SQLException{
    		
    		Connect conn = new Connect();
            Statement st = conn;//.createStatement();
            ResultSet rs = st.executeQuery("select * from Admin WHERE AdminID = 3");
            while(rs.next())
            {
            	System.out.println(rs.getString("Username"));
            }
    	}
    }
    java.lang.NoSuchMethodError: main
    Exception in thread "main"

  • #4
    Senior Coder angst's Avatar
    Join Date
    Apr 2004
    Location
    Toronto, Ontario
    Posts
    2,114
    Thanks
    15
    Thanked 122 Times in 122 Posts
    hmm, I've updated SqlMethods to:

    Code:
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class SqlMethods{
    
    	public SqlMethods() throws SQLException{
    		
    		Connect conn = Connect.getInstance();
    		
            Statement st = (Statement) conn;//.createStatement();
            ResultSet rs = st.executeQuery("select * from Admin WHERE AdminID = 3");
            while(rs.next())
            {
            	System.out.println(rs.getString("Username"));
            }
    	}
    }
    but still no luck, same error:

    java.lang.NoSuchMethodError: main
    Exception in thread "main"

  • #5
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    The main is required for something to run. Where it is depends on what you are doing. Since the SQLMethods is using the Connect class, the connect class itself doesn't want it. It doesn't sound like SQLMethods should be a runnable class either, but you can still test it with a simple:
    PHP Code:
    public static void main(String[] argv)
    {
        try
        {
            new 
    SqlMethods();
        }
        catch (
    SQLException ex)
        {
            
    System.out.println(ex.getMessage());
        }

    And put that in the SqlMethods class.
    Think of your main as the entrance point to your program. If you create a jar file, one of the steps is to adjust the manifest file to determine which class will have the entrance point, and that class must have a main method.
    Edit:
    Oh, I should mention as well. Almost every class I make in java has a main method. But its purpose is to test the class by itself with as little dependency on other classes as possible. Obviously with a SQLMethods you will need a dependency on the Connect class so that is certainly fine. I just won't use these classes as entrance point, I will use the class that uses these classes as the entrance point instead. So what I'm getting at is that the main method itself never needs to be removed, but only 1 main method will be called by your java program.
    Last edited by Fou-Lu; 11-11-2010 at 05:34 PM.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)

  • #6
    Senior Coder angst's Avatar
    Join Date
    Apr 2004
    Location
    Toronto, Ontario
    Posts
    2,114
    Thanks
    15
    Thanked 122 Times in 122 Posts
    hmm, ok I think I see what your saying here.

    so main ( the default for the class ) is kind of like a hook for the program? like a starting position?

    I've added main to SqlMethods as you said, I'm getting a few errors, but I don't really understand what they mean.

    Code:
    import java.sql.Connection;
    import java.sql.DriverManager;
    
    public class Connect
    {
    	private Connection conn;
    
    	public Connect(){
    	        conn = null;
    
    	        try
    	        {
    	            Class.forName ("com.mysql.jdbc.Driver").newInstance ();
    	            conn = DriverManager.getConnection ("jdbc:mysql://172.25.0.3:3306/dev", "dev", "dev");
    	            System.out.println ("Database connection established");
    	        }
    	        catch (Exception e)
    	        {
    	            System.err.println ("Cannot connect to database server");
    	            //e.printStackTrace();
    	            //System.out.println("Exception: " + e.getMessage());
    	        }
    	        finally
    	        {
    	            if (conn != null)
    	            {
    	                try
    	                {
    	                    conn.close ();
    	                }
    	                catch (Exception e) { /* ignore close errors */ }
    	            }
    	        }
    	}
    
    	public static Connect getInstance() {
    		// TODO Auto-generated method stub
    		return null;
    	} 
    
    }
    Code:
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class SqlMethods{
    
    	public SqlMethods() throws SQLException{
    		
    	Connect conn = Connect.getInstance();
    
            Statement st = (Statement) conn;//.createStatement();
            ResultSet rs = st.executeQuery("select * from Admin WHERE AdminID = 3");
            while(rs.next())
            {
            	System.out.println(rs.getString("Username"));
            }
    	}
    
    	public static void main(String[] argv)
    	{
    	    try
    	    {
    	        new SqlMethods();
    	    }
    	    catch (SQLException ex)
    	    {
    	        System.out.println(ex.getMessage());
    	    }
    	}
    }


    Thread [main] (Suspended (exception NullPointerException))
    SqlMethods.<init>() line: 14
    SqlMethods.main(String[]) line: 25

  • #7
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    The exception indicates you are interacting with a non-object, probably the st.executeQuery (I don't expect that the cast of conn to a Statement made it very happy):
    PHP Code:
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;

    public class 
    SqlMethods{

        public 
    SqlMethods() throws SQLException{
            
        
    Connect conn Connect.getInstance();

            
    Statement st conn.createStatement();
            
    ResultSet rs st.executeQuery("select * from Admin WHERE AdminID = 3");
            while(
    rs.next())
            {
                
    System.out.println(rs.getString("Username"));
            }
        }

        public static 
    void main(String[] argv)
        {
            try
            {
                new 
    SqlMethods();
            }
            catch (
    SQLException ex)
            {
                
    System.out.println("SQL Exception: " ex.getMessage());
            }
                catch (
    Exception e)
                {
                    
    System.out.println("Generic Exception: " e.getMessage());
                }
        }

    Does that work?
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)

  • #8
    Senior Coder angst's Avatar
    Join Date
    Apr 2004
    Location
    Toronto, Ontario
    Posts
    2,114
    Thanks
    15
    Thanked 122 Times in 122 Posts
    that gives me: Generic Exception: null

  • #9
    Senior Coder angst's Avatar
    Join Date
    Apr 2004
    Location
    Toronto, Ontario
    Posts
    2,114
    Thanks
    15
    Thanked 122 Times in 122 Posts
    i wonder, in the connect class:

    Code:
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    public class Connect
    {
    	private Connection conn;
    
    	public Connect(){
    	        conn = null;
    
    	        try
    	        {
    	            Class.forName ("com.mysql.jdbc.Driver").newInstance ();
    	            conn = DriverManager.getConnection ("jdbc:mysql://172.25.0.3:3306/dev", "dev", "dev");
    	            System.out.println ("Database connection established");
    	        }
    	        catch (Exception e)
    	        {
    	            System.err.println ("Cannot connect to database server");
    	            //e.printStackTrace();
    	            //System.out.println("Exception: " + e.getMessage());
    	        }
    	        finally
    	        {
    	            if (conn != null)
    	            {
    	                try
    	                {
    	                    conn.close ();
    	                }
    	                catch (Exception e) { /* ignore close errors */ }
    	            }
    	        }
    	}
    
    	public static Connect getInstance() {
    		// TODO Auto-generated method stub
    		return null;
    	}
    
    	public ResultSet executeQuery(String string) {
    		// TODO Auto-generated method stub
    		return null;
    	}
    
    	public Statement createStatement() {
    		// TODO Auto-generated method stub
    		return null;
    	} 
    
    }
    shouldn't getInstance() return something?

  • #10
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    Change the println from the Exception catch to:
    PHP Code:
    catch (Exception e)
    {
        
    e.printStackTrace();

    And post the error result. That should show what is throwing the nullpointer.

    Edit:
    Been awhile myself, but no I don't think you need to capture the results of it. What that should do is return the classname for use by the jdbc. You can capture it, but Its not really necessary.
    Last edited by Fou-Lu; 11-12-2010 at 12:16 AM.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)

  • #11
    Senior Coder angst's Avatar
    Join Date
    Apr 2004
    Location
    Toronto, Ontario
    Posts
    2,114
    Thanks
    15
    Thanked 122 Times in 122 Posts
    that gives me:


    java.lang.NullPointerException
    at Lib.SqlMethods.<init>(SqlMethods.java:13)
    at Lib.SqlMethods.main(SqlMethods.java:25)

  • #12
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    What is line 13 on the SqlMethods? My count puts me at the try which shouldn't cause any issue whatsoever.

    [edit]
    Sorry, I was looking at the Connect class.
    That drops on rs.next(). When you walk this through the debugger, is it triggered on the executeQuery or the next call?
    Edit:
    Oh wait, now I see it. You're trying to use Connect.getInstance. All this does is return null, if you want that to be a singleton class you need to implement a static Connect (not the Connection) variable within the Connect class, and use this for the getInstance:
    PHP Code:
    public static Connect getInstance()
    {
        if (
    myConnect == null// I called the var myConnect
        
    {
            
    myConnect = new Connect();
        }
        return 
    myConnect;

    Last edited by Fou-Lu; 11-12-2010 at 12:23 AM.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)

  • #13
    Senior Coder angst's Avatar
    Join Date
    Apr 2004
    Location
    Toronto, Ontario
    Posts
    2,114
    Thanks
    15
    Thanked 122 Times in 122 Posts
    line 13 is:


    ResultSet rs = st.executeQuery("select * from Admin WHERE AdminID = 3");

  • #14
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    Quote Originally Posted by angst View Post
    line 13 is:


    ResultSet rs = st.executeQuery("select * from Admin WHERE AdminID = 3");
    Check my edit, I noticed after you mentioned the getInstance() - I thought you meant the newInstance() from the Class.forname call.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)

  • #15
    Senior Coder angst's Avatar
    Join Date
    Apr 2004
    Location
    Toronto, Ontario
    Posts
    2,114
    Thanks
    15
    Thanked 122 Times in 122 Posts
    hmm, i'm pretty confused here. ( sorry to be a pain ).

    I replaced getInstance() with your snippet, however now I get this:


    Exception in thread "main" java.lang.Error: Unresolved compilation problems:
    myConnect cannot be resolved to a variable
    myConnect cannot be resolved to a variable
    myConnect cannot be resolved to a variable

    at Lib.Connect.getInstance(Connect.java:42)
    at Lib.SqlMethods.<init>(SqlMethods.java:10)
    at Lib.SqlMethods.main(SqlMethods.java:24)


    this seem more difficult than I had expected.


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •