Java数据库最小化连接创建 [英] Java Database minimize connection creation

查看:90
本文介绍了Java数据库最小化连接创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am a very beginner to Java and for one of my assignments. I have to do database operations. I have this Java code for inserting data to a database and it works fine.

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
}

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

My question is every time the code runs, my code has to create a database connection and prepared statement objects and as I understand it is a costly operation.

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

Is there any way that I can keep a single connection to database and use that to perform my database work?

推荐答案

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

You can use the design pattern Singleton Connection like this :

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

1- create a class SingletonConnection.java look like that :

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


}

并在你的其他类称之为:

And in your other class call it like that :

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

这篇关于Java数据库最小化连接创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆