Encapsulates a tool class to enable JDBC to connect to a MySQL database

Source: Internet
Author: User
Tags stmt

Package COM.CN.JDBC;

Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import java.sql.Statement;

Public class Jdbc_connection {

//Load driver, link database
public static Connection getconnection () throws SQLException,
classnotfoundexception{
Class.forName ("Com.mysql.jdbc.Driver");
String url= "Jdbc:mysql://localhost:3306/rentbikes";
String username= "root";
String password= "000000";
Connection conn=drivermanager.getconnection (URL, username, password);
Return conn;
}
//Close database connection, free resources
public static void release (Statement stmt,connection conn) {
if (stmt!=null) {
try{
Stmt.close ();
}catch (SQLException e) {
E.printstacktrace ();
}
Stmt=null;
}
if (conn!=null) {
try{
Conn.close ();
} catch (SQLException e) {
E.printstacktrace ();
}
Conn=null;
}
}
public static void release (ResultSet rs,statement stmt,connection conn) {
if (rs!=null) {
try{
Rs.close ();
}catch (SQLException e) {
E.printstacktrace ();
}
Rs=null;
}
Release (Stmt,conn);
}
}

Summary: Because each time the database is operational, it is necessary to load the database driver, establish a database connection and close the database connection, this tool class can avoid the duplication of code writing.

Encapsulates a tool class to enable JDBC to connect to a MySQL database

Related Article

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.