0

i newbie in Java.

I want create small application, which connect to MySQL and execute some queries.

My real problem - connect to mysql, and keep this connection for other classes, without opening connection again and again.

I read documentation about MVC and OOP. But i still can't understand how i can resolve this problem.

As i imagine, i should inherit a database class in models, like user and messages from mypackage. But i don't imagine how it should looks.

I already tried search some examples in google, but i found only simple example with one main class and database class.

So, i need someone, who can explain it for me

I will be grateful for any help

User class

package mypackage;
class user {
    public String getName() {
        // return value from mysql
    }
}

Messages class

package mypackage;
class messages {
    public String getMessage() {
        // return value from mysql
    }
}

Database class

package database;
class db {
        private String dbUri = "jdbc:mysql://";
    private String dbDriver = "com.mysql.jdbc.Driver";
    private Connection connection;

    public boolean connect(String host, String base, String user, String pass)
    {
        try {
            Class.forName(dbDriver);
            String uri = dbUri + host + '/' + base;
            connection = DriverManager.getConnection(uri, user, pass);
            return true;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return false;
            // Could not find the database driver
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
            // Could not connect to the database
        }
    }
}

Main class

import mypackage.*;
import database.*;

class main
{
    public static void main(String[] args)
    {
        database db = new database();
                user usr = new user();
                System.out.println(usr.getName());
                messages msg = new messages();
                System.out.println(msg.getMessage());
    }
}

3 Answers 3

4

Your db class stores connection already so just create means to retrieve it:

package database;
class Database {
    private String dbUri = "jdbc:mysql://";
    private String dbDriver = "com.mysql.jdbc.Driver";
    private Connection connection;

    public boolean connect(String host, String base, String user, String pass)  {
       try {
            Class.forName(dbDriver);
            String uri = dbUri + host + '/' + base;
            connection = DriverManager.getConnection(uri, user, pass);
            return true;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return false;
            // Could not find the database driver
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
            // Could not connect to the database
        }
    }

    public Connection getConnection() {
        return connection;
    }
}

In your main:

class Main
{
    public static void main(String[] args)
    {
        Database db = new Database();
        if (db.connect(/* parameters for database connection here */)) {
            final Connection conn = db.getConnection();
            // you can use conn for your queries. If they are in other classes, pass connection as parameter.
        }
    }
}

I've tried to make it simple, but you should actually use factory and singleton patterns to create and store a connection, once created, and then statically retrieve it within application. Once you feel comfortable with the concept you should also look into connection pooling as suggested in comments, for example with use of BoneCP.

Sign up to request clarification or add additional context in comments.

8 Comments

I'd like to slightly correct you. He should actually use a connection pool (like BoneCP) and Dependency Injection (like Guice) to retrieve it, and get his connections from that. Your example is pretty close.
You are of course right, but that is even higher level of complexity :)
Very interesting. Do you can recommend some documentation about connection pool?
@ВикторНовиков Sure. The quickest way is just to visit the BoneCP website: jolbox.com and read their tutorials. But basically a Connection Pool is functionality that takes care of handling your JDBC connections for you. It will handle getting and freeing connections for you, and allow you to reuse connections (allocating a connection is a fairly expensive operation). This is of course most useful in an environment where you have lots of different threads, that all require their own connection to the DB ( for transactions etc.) like a Java EE or Swing application.
I think for very basic applications I would stick to simple solutions and then perhaps upgrade them to make use of more advanced techniques, once you feel comfortable with the whole idea. Using techniques like connection pooling surely creates good habits but it might confuse you a bit in the beginning.
|
1

Note: This is not an answer to the question, this is an answer to the follow up question about a correct example of a Singleton pattern. I know this is technically not how SO works. But the question isn't really SO material anyway.

Ok, so there are a few different strategies for creating a Singleton, the one I've chosen to show is the classical Singleton pattern, which works for anything, regardless of what frameworks you're using. Of course if you're using a Dependency Injection / Inversion of Control container, like Guice or Spring (beans) you should follow those guidelines instead of these.

First the code:

public final class ClassicSingleton {

    private static ClassicSingleton instance; 
    private final String exampleImmutable = "My state cannot be changed.";
    private String exampleMutable = "My state can be changed.";

    private ClassicSingleton() {
    }

    public static ClassicSingleton getInstance() {
        if (instance == null)
            instance = new ClassicSingleton();
        return instance;
    }

    public String getExampleImmutable() {
        return exampleImmutable;
    }

    public String getExampleMutable() {
        return exampleMutable;
    }

    public void setExampleMutable(String exampleMutable) {
        this.exampleMutable = exampleMutable;
    }
}

Now, the first thing to note is that it has a private Constructor, this is to prevent Java from using the default constructor. It also makes sure that only the ClassicSingleton class can create ClassicSingleton objects. Since this is only done in one place, and since that one place is only invoked once, we have enforced, through code that there can be only one instance of this object at any given time. Further more, this particular implementation is lazy instantiated (it is created the first time you need it. Whether this is useful depends on what kind of application you're writing.

The second thing to note is that the class is final, you cannot inherit from it. While this technically isn't possible anyway (because the constructor is private) it's a nice to have for completeness.

The thing that completes it is the static instance variable and static accessor, which let's you get the instance variable. This gives the Singleton global accessibility. Generally, when a class has a getInstance() method it's safe to assume it's a Singleton. This is a convention.

Lastly the example contains examples of immutable and mutable members. Which type you need depends on your specific needs.

Anyway, I hope I helped clear some things up for you.

Comments

0

You need to have in this manner to share the connection between classes,

Provider.java, an interface that contains many constants like DRIVER_CLASS, CONNECTION_URL, USERNAME and PASSWORD

ConnectionProvider.java, a class that is responsible to return the object of Connection. It uses the Singleton and factory method design pattern.

Interface :

public interface Provider {
String DRIVER="driver_name";
String CONNECTION_URL="URL";
String USERNAME="";
String PASSWORD="";
}

ConnectionProvider class:

public class ConnectionProvider {
private static Connection con=null;
static{
try{
Class.forName(DRIVER);
con=DriverManager.getConnection(CONNECTION_URL,USERNAME,PASSWORD);
}catch(Exception e){}
}

public static Connection getCon(){
    return con;
}    
}

And in your Dao classes , create an object for connection and use it ,

Connection con=ConnectionProvider.getCon();

Hope this helps!!

6 Comments

Thankyou very much! It's something what i need :) If i not mistaken, it Singleton pattern :)
Yes it is singleton pattern . please be more clear with your question
I tried to be more clear... it all because of language barrier, i not good in English yet, but i try to learn and learn and learn. Sorry for my mistakes. And thanks again for your help
No issues :) Happy to help :)
@sankrish First of all it's not a Singleton, because you can create as many instances as you want. Secondly it's not a Factory Pattern either, because it does not create objects. It's a static class which contains a (mutable!) Connection field. This means that calling close() or setAutoCommit() in one part of your code, can potentially break other parts of your code, giving a high coupling, which is an anti-pattern.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.