Jdbcutils class:
1. Create a private property * (four variables necessary to connect to the database): Dreiver URL user password
2. Privatize the constructor
3. Write the registration drive to a static block of code
4. The outside world can only get the database connection by invoking the static method of the tool Getconnectio (), allowing the caller to handle the exception (throwing an exception)
5. Resource closure using static method calls
Packagecom.test.utils;Importjava.sql.Connection;ImportJava.sql.DriverManager;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.sql.Statement; Public Final classJdbcutils {Private StaticString driver= "Com.mysql.jdbc.Driver"; Private StaticString url= "Jdbc:mysql://localhost:3306/store28"; Private StaticString user= "Root"; Private StaticString password= "root1234"; Privatejdbcutils () {}Static { /*** Driver Registration*/ Try{class.forname (driver); } Catch(ClassNotFoundException e) {Throw NewExceptionininitializererror (e); } } /*** Get connetion *@return * @throwsSQLException*/ Public StaticConnection getconnection ()throwssqlexception{returndrivermanager.getconnection (URL, user, password); } /*** Release Resources *@paramConn *@paramSt *@paramRS*/ Public Static voidColseresource (Connection conn,statement st,resultset rs) {closeresultset (RS); Closestatement (ST); CloseConnection (conn); } /*** Release Connection Connection *@paramConn*/ Public Static voidCloseConnection (Connection conn) {if(Conn! =NULL) { Try{conn.close (); } Catch(SQLException e) {e.printstacktrace (); } } //Waiting for garbage collectionconn =NULL; } /*** Release Statement performer Statement *@paramSt*/ Public Static voidClosestatement (Statement St) {if(St! =NULL) { Try{st.close (); } Catch(SQLException e) {e.printstacktrace (); } } //Waiting for garbage collectionSt =NULL; } /*** Release result set ResultSet *@paramRS*/ Public Static voidCloseresultset (ResultSet rs) {if(rs! =NULL) { Try{rs.close (); } Catch(SQLException e) {e.printstacktrace (); } } //Waiting for garbage collectionrs =NULL; }}
Tool Testing:
Packagecom.test.utils;Importjava.sql.Connection;Importjava.sql.PreparedStatement;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importorg.junit.Test; Public classjdbctest {@Test Public voidAdd () {Connection conn=NULL; PreparedStatement St=NULL; ResultSet RS=NULL; Try { //Get Connectionsconn =jdbcutils.getconnection (); //Writing SQLString sql = "INSERT into category values (?,?)"; //Create statement performerst=conn.preparestatement (SQL); //Setting ParametersSt.setstring (1, "10"); St.setstring (2, "Test Catalog"); //Execute SQL inti =st.executeupdate (); if(i==1) {System.out.println ("Data added successfully!" "); }Else{System.out.println ("Data addition failed!" "); } } Catch(SQLException e) {e.printstacktrace (); }finally{jdbcutils.colseresource (conn, St, RS); } }}
Custom JDBC Connection Tool class Jdbcutils "Java Tools Class"