java连接Mysql数据库的工具类
一个封装好的链接Mysql数据库的工具类,可以方便的获取Connection对象关闭Statement、ResultSet、Statment对象等等
packagemyUtil;
importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.PreparedStatement;
importjava.sql.ResultSet;
importjava.sql.SQLException;
importjava.sql.Statement;
/**
*链接mysql数据库
*@authorweichk
*/
publicclassMysqlDbManager{
privatestaticfinalStringURL="jdbc:mysql://127.0.0.1:3306/openfire";
privatestaticfinalStringUSER="root";
privatestaticfinalStringPASSWORD="123456";
static{
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundExceptione){
System.out.println("加载Mysql数据库驱动失败!");
}
}
/**
*获取Connection
*
*@return
*@throwsSQLException
*@throwsClassNotFoundException
*/
publicstaticConnectiongetConnection()throwsSQLException{
Connectionconn=null;
try{
conn=DriverManager.getConnection(URL,USER,PASSWORD);
}catch(SQLExceptione){
System.out.println("获取数据库连接失败!");
throwe;
}
returnconn;
}
/**
*关闭ResultSet
*@paramrs
*/
publicstaticvoidcloseResultSet(ResultSetrs){
if(rs!=null){
try{
rs.close();
}catch(SQLExceptione){
System.out.println(e.getMessage());
}
}
}
/**
*关闭Statement
*@paramstmt
*/
publicstaticvoidcloseStatement(Statementstmt){
if(stmt!=null){
try{
stmt.close();
}
catch(Exceptione){
System.out.println(e.getMessage());
}
}
}
/**
*关闭ResultSet、Statement
*@paramrs
*@paramstmt
*/
publicstaticvoidcloseStatement(ResultSetrs,Statementstmt){
closeResultSet(rs);
closeStatement(stmt);
}
/**
*关闭PreparedStatement
*@parampstmt
*@throwsSQLException
*/
publicstaticvoidfastcloseStmt(PreparedStatementpstmt)throwsSQLException
{
pstmt.close();
}
/**
*关闭ResultSet、PreparedStatement
*@paramrs
*@parampstmt
*@throwsSQLException
*/
publicstaticvoidfastcloseStmt(ResultSetrs,PreparedStatementpstmt)throwsSQLException
{
rs.close();
pstmt.close();
}
/**
*关闭ResultSet、Statement、Connection
*@paramrs
*@paramstmt
*@paramcon
*/
publicstaticvoidcloseConnection(ResultSetrs,Statementstmt,Connectioncon){
closeResultSet(rs);
closeStatement(stmt);
closeConnection(con);
}
/**
*关闭Statement、Connection
*@paramstmt
*@paramcon
*/
publicstaticvoidcloseConnection(Statementstmt,Connectioncon){
closeStatement(stmt);
closeConnection(con);
}
/**
*关闭Connection
*@paramcon
*/
publicstaticvoidcloseConnection(Connectioncon){
if(con!=null){
try{
con.close();
}
catch(Exceptione){
System.out.println(e.getMessage());
}
}
}
}
以上就是本文的全部内容了,希望对大家熟练掌握java能有所帮助。