Tool classes do not need to be inherited
Public final class jdbcutils{
Encapsulates database connection parameters for late change of parameter values
private static String url= "JDBC:MYSQL://LOCALHOST:3306/JDBC";
private static String user= "UserName";
private static String password= "password";
No objects to be created
Private Jdbcutils () {}
Static code block: Executes at project start time
static{
try{
Class.forName ("Com.mysql.jdbc.Driver");
}catch (ClassNotFoundException e) {
throw new Ininitializererror (e);
}
}
Create a database connection
public static Connection Getconnetcion () throws sqlexception{
Return drivaermanager.getconnetcion (Url,user,password);
}
Freeing resources
public static void FreeResource (ResultSet resultset,statement statement,connection conn) {
try{
if (resultset!=null)
Resultset.close ();
}catch (SQLException e) {
E.printstacktrace ();
}finally{
try{
if (statement!=null)
Statement.close ();
}catch (SQLException e) {
E.printstacktrace ();
}finally{
try{
if (conn!=null)
Conn.close ();
}catch (SQLException e) {
E.printstacktrace ();
}
}
}
}
}
Example
public class userdao{
public static void Testgetusers () throws exception{
Connection Conn=null;
Statement Statement=null;
ResultSet Resultset=null;
try{
Conn=jdbcutils.getconnetcion ();
Statement=conn.createstatement ();
Resultset=statement.excutequery ("SELECT * from user");
while (Resultset.next ()) {
System.out.println (Resultset.getobject (1) + "\ T" +resultset.getobject (2));
}
}finally{
Jdbcutils.freeresource (Resultset,statement,conn);
}
}
}
Beginner JDBC,JDBC Simple Package for tool class