简体   繁体   English

用Java建立与数据库的持久连接

[英]Establishing persistent connection to a database in Java

I've ran through several examples over the web, and found that every single time I need something from the DB, I should write the following code: 我在网上浏览了几个示例,发现每次我需要数据库中的东西时,我都应该编写以下代码:

try
{
  // Step 1: Load the JDBC driver. 
  Class.forName("mysql_driver_name"); 
  // Step 2: Establish the connection to the database. 
  String url = "jdbc:string_to_mysql_server"; 
  Connection conn = DriverManager.getConnection(url,"user1","password");

  // fetch from the DB ...

}
catch (Exception e)
{
  System.err.println("Got an exception! "); 
  System.err.println(e.getMessage()); 
}

It's very annoying to put up this code every time I want something from the DB, so the question is - is there a way to only once connect entirely all my app to the DB somehow at the very start point, avoiding copy-pasting mentioned code, and then be able to do everything I want with DB? 每当我想要从数据库中获取某些代码时,都会很烦人,所以问题是-有没有办法在开始时以某种方式将我所有的应用程序一次全部连接到数据库,避免复制粘贴所提到的代码,然后能够使用DB 做我想做的所有事情

I've quickly looked through NetBeans's Project menu, but didn't find any clue on how to configurate a persistent connection to a selected DB. 我快速浏览了NetBeans的“项目”菜单,但没有找到有关如何配置与所选数据库的持久连接的任何线索。

If it's important, i'm writing a purely desktop app, ie using Java SE. 如果重要的话,我正在编写一个纯粹的桌面应用程序,即使用Java SE。 Also, it's worth mentioning that I'm a kinda beginner in Java. 另外,值得一提的是,我是Java的初学者。

有很多连接池选项可供选择,我建议您尝试使用Apache Common Db连接池http://commons.apache.org/dbcp/

The connection pool idea is probably the best overal solution. 连接池的想法可能是最好的总体解决方案。 However there is a simpler one in ypur case. 但是在ypur案例中有一种更简单的方法。

In your code conn goes out of scope in the method itwas created. 在您的代码中,conn超出了其创建方法的范围。 There is no need to do that. 不需要这样做。 You can create a method that includes all your code up to an including the line that assigns to conn. 您可以创建一个方法,该方法包括所有代码,直到一个包含分配给conn的行。 Then pass that conn variable to other parts of the program and use that for db work. 然后将该conn变量传递给程序的其他部分,并将其用于数据库工作。

You can follow this Method of Establishing the Conenction 您可以按照这种建立对接方法

  1. Create a Singleton class, which helps you to create a connection 创建一个Singleton类,可帮助您创建连接
  2. In your DAO or any helper Class, Call this Single instance, which has a connection 在您的DAO或任何帮助程序类中,调用此具有连接的Single实例
  3. Once you get the Conenction, write the operations that you want to perform on the database. 一旦获得连接,请编写要在数据库上执行的操作。
  4. Close the connection, that will do to fullfill your connection. 关闭连接,这将完全填满您的连接。

This will avoid the code, what you have written in your query. 这将避免使用您在查询中编写的代码。 and this style will increases the readability and reduce the maintainability. 并且这种样式将增加可读性并降低可维护性。

If you want any sample code let me know, I can provide you that 如果您想让我知道任何示例代码,我可以为您提供

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

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