简体   繁体   中英

Java. Share MySQL connection between classes

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());
    }
}

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 .

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.

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!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM