Establishing persistent connection to a database in Java
- by gmile
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?
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.
If it's important, i'm writing a purely desktop app, i.e. using Java EE. Also, it's worth mentioning that I'm a kinda beginner in Java.