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

gmi*_*ile 1 java mysql database

我在网上浏览了几个例子,发现每次我需要DB的东西,我都应该编写以下代码:

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()); 
}
Run Code Online (Sandbox Code Playgroud)

每次我想要来自数据库的东西时都会提出这个代码是非常讨厌的,所以问题是 - 有没有办法只在一开始就将我的所有应用程序完全连接到数据库,避免复制粘贴提到的代码,然后能够用DB 做我想做的一切吗?

我已经快速查看了NetBeans的Project菜单,但没有找到任何关于如何配置与所选DB的持久连接的线索.

如果它很重要,我正在编写一个纯桌面应用程序,即使用Java SE.此外,值得一提的是,我是Java的初学者.

cro*_*wne 5

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