Java数据库最小化连接创建

时间:2017-08-26 04:21:49

标签: java mysql sql jdbc

我是Java的初学者和我的任务之一。我必须做数据库操作。我有这个用于将数据插入数据库的Java代码,它工作正常。

public class JavaDBWork
{

  public static void main(String[] args)
  {
    try
    {
      // create a mysql database connection
      String myDriver = "org.gjt.mm.mysql.Driver";
      String myUrl = "jdbc:mysql://localhost/test";
      Class.forName(myDriver);
      Connection conn = DriverManager.getConnection(myUrl, "root", "");

      // create a sql date object so we can use it in our INSERT statement
      Calendar calendar = Calendar.getInstance();
      java.sql.Date startDate = new java.sql.Date(calendar.getTime().getTime());

      // the mysql insert statement
      String query = " insert into users (first_name, last_name, date_created, is_admin, num_points)"
        + " values (?, ?, ?, ?, ?)";

    //Other Code
}

我的问题是每次代码运行时,我的代码都必须创建一个数据库连接和准备好的语句对象,据我所知,这是一个代价高昂的操作。

有什么方法可以保持与数据库的单一连接并使用它来执行我的数据库工作?

2 个答案:

答案 0 :(得分:3)

您可以像这样使用设计模式Singleton Connection:

1-创建一个类SingletonConnection.java,如下所示:

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

public class SingletonConnection   {


    private static Connection connection = null ;
    static 
    {
        try{
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection
                    ("jdbc:mysql://localhost:3306/gestion_comptes","root","");
        }catch(Exception ex)
        {

        }

    }
    public static Connection getConnection() throws Exception {
        return connection;
    }


}

在你的其他课堂上称之为:

 public  class DaoImpl{

        public Connection connection = SingletonConnection.getConnection();

        public DaoImpl() throws Exception 
        {
            if(connection==null)
                throw new Exception("impossible de se connecter à la base de données");
        }
}

答案 1 :(得分:2)

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Calendar;

public class JavaDBWork {

    private final String DATBASE = "myDatabasename";
    private final String URL = "jdbc:mysql://localhost:3306/" + DATBASE + "?useSSL=false";
    private final String USERNAME = "myUsername";
    private final String PASSWORD = "myPassword";

    private Connection databaseConnection;

    // Main Method to init
    public static void main(String[] args) {
        // build an javaDBWork with init connection one time
        JavaDBWork javaDBWork = new JavaDBWork();
        // call methods in javaDBWork you like
        javaDBWork.doSomething();
    }

    public JavaDBWork() {
        // create a mysql database connection at init
        this.databaseConnection = databaseConnection();
    }

    private Connection databaseConnection() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return connection;
    }

    public void doSomething() {
        try {
            // create a sql date object so we can use it in our INSERT statement
            Calendar calendar = Calendar.getInstance();
            java.sql.Date startDate = new java.sql.Date(calendar.getTime().getTime());

            // the mysql insert statement       
            String sql = " insert into users (first_name, last_name, date_created, is_admin, num_points)" + " values (?, ?, ?, ?, ?)";
            PreparedStatement preparedStatement = null;

            preparedStatement = databaseConnection.prepareStatement(sql);
            preparedStatement.setString(1, "Lucky");
            preparedStatement.setString(2, "Luke");
            ...

            preparedStatement.executeUpdate();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

你可以这样做。

初始化数据库连接一次,并在您需要时调用的对象中保持连接。

编辑: 需要在另一个类中进行连接时的示例:

public class MyMainClass {

    private JavaDBWork javaDBWork;

    // Main Method to init
    public static void main(String[] args) {
        new MyMainClass();
    }

    public MyMainClass() {
        // build an javaDBWork with init connection one time
        javaDBWork = new JavaDBWork();
        // call methods in javaDBWork you like
        javaDBWork.doSomething();
    }

}


public class JavaDBWork {

    private final String DATBASE = "myDatabasename";
    private final String URL = "jdbc:mysql://localhost:3306/" + DATBASE + "?useSSL=false";
    private final String USERNAME = "myUsername";
    private final String PASSWORD = "myPassword";

    private Connection databaseConnection;

    public JavaDBWork() {
        // create a mysql database connection at init
        this.databaseConnection = databaseConnection();
    }

    private Connection databaseConnection() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return connection;
    }

    public void doSomething() {
        try {
            // create a sql date object so we can use it in our INSERT statement
            Calendar calendar = Calendar.getInstance();
            java.sql.Date startDate = new java.sql.Date(calendar.getTime().getTime());

            // the mysql insert statement
            String sql = " insert into users (first_name, last_name, date_created, is_admin, num_points)" + " values (?, ?, ?, ?, ?)";
            PreparedStatement preparedStatement = null;

            preparedStatement = databaseConnection.prepareStatement(sql);
            preparedStatement.setString(1, "Lucky");
            preparedStatement.setString(2, "Luke");

            preparedStatement.executeUpdate();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}