简体   繁体   English

JDBC的各种连接

[英]JDBC kinds of connection

I'm creating app for library management with Java and MySQL ( JDBC to connect with DB ) , and I have a problem , I checked a lot of topics, books, and websites but I didn't find good answer for me. 我正在使用Java和MySQL(用于连接DB的JDBC)创建用于图书馆管理的应用程序,但是我遇到了问题,我检查了很多主题,书籍和网站,但找不到适合我的答案。 Is it the good way to deal with connections ? 这是处理连接的好方法吗? I think that one connection for entire app is good option in this case. 我认为在这种情况下,整个应用程序的一个连接是一个不错的选择。 My idea is that in every function in every class when I need to use Connection object , these functions will need a connection parameter. 我的想法是,在每个类的每个函数中,当我需要使用Connection对象时,这些函数都需要一个连接参数。 In main class I'll call manager object 'Man' for example and to every constructor etc I'll pass Man.getMyConn() as this parameter and call Man.close() when Main frame will be closed . 在主类中我会打电话给经理对象“人”的榜样,每一个构造等我会通过Man.getMyConn()为这个参数,并调用Man.close()时,主框架将被关闭。 Is it bad idea ? 这是个坏主意吗? Maybe I should use singleton pattern or connection pool ? 也许我应该使用单例模式或连接池? Sorry for my English , I'm still learning. 对不起,我的英语,我还在学习。

public class manager {
private Connection myConn;

public manager() throws Exception {


    Properties props = new Properties();
    props.load(new FileInputStream("app.properties"));

    String user = props.getProperty("user");
    String password = props.getProperty("password");
    String dburl = props.getProperty("dburl");


    myConn = DriverManager.getConnection(dburl, user, password);
    System.out.println("DB connection successful to: " + dburl);
}

public Connection getMyConn() {
    return myConn;
}
  //close class etc.
}

Usually not. 通常不会。 Further answer depends on type of the application. 进一步的答案取决于应用程序的类型。 If you're making web application then you should definitely go with connection pool. 如果要制作Web应用程序,则绝对应该使用连接池。 If you're making eg desktop application (where only one user can access it at the time), then you can open and close connection upon each request. 如果您正在制作桌面应用程序(当时只有一个用户可以访问它),那么您可以根据每个请求打开和关闭连接。

I have working applications that do it your way. 我的工作应用程序可以按照您的方式进行。 As @Branislav says, it's not adequate if you want to do multiple concurrent queries. 正如@Branislav所说,如果要执行多个并发查询,这是不够的。 There's also a danger that the connection to the database might be lost, and you would need to restart your application to get a new one, unless you write code to catch that and recreate the connection. 还存在与数据库的连接可能丢失的危险,并且除非需要编写代码来捕获并重新创建连接,否则您需要重新启动应用程序以获取新的应用程序。

Using a singleton would be overcomplicated. 使用单例会过于复杂。 Having a getConnection() method (as you have done) is very important as it means you can easily change your code to use a pool later if you find you need to. 拥有getConnection()方法(已完成)非常重要,因为这意味着您可以轻松地更改代码以在以后需要时使用池。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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