Beginner JDBC,JDBC Simple Package for tool class

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.