Java独立应用程序中静态连接对象的缺点 [英] Disadvantages of static Connection object in Java standalone application

查看:112
本文介绍了Java独立应用程序中静态连接对象的缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java还是很陌生,并且正在与GUI构建器一起玩耍,以学习Java的一些OO和其他编程概念.

I'm still pretty new to Java and was playing around with the GUI builder to learn some of Java's OO and other programming concepts.

我创建了一个非常基本的银行系统,客户基本上可以在其中存钱和取钱.

I created a very basic banking system where customer can deposit money and withdraw money, basically.

我的代码没有特别的问题,因为一切正常,我只是有关于数据库连接的问题.

I don't particularly have a problem with my code as everything works, I just have a problem about database connections.

由于总是重复创建连接的代码,因此我创建了一个数据库类,如下所示:

Since the code to create a connection is always repeated, I created a database class such as below:

public class DB {
    static Connection c;

    public static void createConnection() throws Exception{
        Class.forName("com.mysql.jdbc.Driver");
        DB.c = DriverManager.getConnection("jdbc:mysql://localhost:3306/bank", "root", "");
    }

    public static int insertUpdateDelete(String sql) throws Exception{
        if(c == null){
            createConnection();
        }
        return c.createStatement().executeUpdate(sql);
    }

    public static ResultSet search(String sql) throws Exception{
        if(c == null)
            createConnection();
        return c.createStatement().executeQuery(sql);
    }
}

因此,每当我想从数据库中插入/更新/删除时,我都会这样做:

So whenever I want to insert/update/delete from a database I just did:

DB.insertUpdateDelete(SQL); //SQL contains the query

对于搜索,我会这样做:

And for search I'd do:

ResultSet rs = DB.search(SQL);

经过一番阅读,我了解到由于资源泄漏"和查询相互干扰,拥有静态连接对象并不是最佳实践.

After a bit of reading, I learnt that having static connection objects aren't the best practice due to "resource leaking" and queries interfering with each other.

我的问题是,在一个独立的Java应用程序中获得连接的最佳方法是什么,而不必重复不断地重复相同的代码.

My question is, what is the best way to get the connection in a standalone Java application where one does not have to keep repeating the same code over and over again.

谢谢

推荐答案

通常的方法是连接池.

静态连接对象有问题:

  • 您保留每个用户会话的连接.对于许多用户而言,它明显增加了数据库服务器的负载(或您的许可证成本(如果有)).
  • 如果连接中断或超时,则无法重新建立连接.

每次打开连接都很慢.

连接池保留相当数量的打开的连接,知道如何替换由于错误而断开的连接,并且可以为您提供连接,并很快将其收回.

A connection pool keeps a reasonable number of open connections, knows how to replace those that get disconnected due to an error, and can give you a connection, and take it back, very quickly.

JDBC的连接池有几种实现.

There are several implementations of connection pools for JDBC.

这篇关于Java独立应用程序中静态连接对象的缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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