java连接Mysql数据库的工具类
程序员文章站
2024-03-03 19:21:40
一个封装好的链接mysql数据库的工具类,可以方便的获取connection对象关闭statement、resultset、statment对象等等
复制代码 代码如下:...
一个封装好的链接mysql数据库的工具类,可以方便的获取connection对象关闭statement、resultset、statment对象等等
复制代码 代码如下:
package myutil;
import java.sql.connection;
import java.sql.drivermanager;
import java.sql.preparedstatement;
import java.sql.resultset;
import java.sql.sqlexception;
import java.sql.statement;
/**
* 链接mysql数据库
* @author weichk
*/
public class mysqldbmanager {
private static final string url = "jdbc:mysql://127.0.0.1:3306/openfire";
private static final string user = "root";
private static final string password = "123456";
static {
try {
class.forname("com.mysql.jdbc.driver");
} catch (classnotfoundexception e) {
system.out.println("加载mysql数据库驱动失败!");
}
}
/**
* 获取connection
*
* @return
* @throws sqlexception
* @throws classnotfoundexception
*/
public static connection getconnection() throws sqlexception {
connection conn = null;
try {
conn = drivermanager.getconnection(url, user, password);
} catch (sqlexception e) {
system.out.println("获取数据库连接失败!");
throw e;
}
return conn;
}
/**
* 关闭resultset
* @param rs
*/
public static void closeresultset(resultset rs) {
if (rs != null) {
try {
rs.close();
} catch (sqlexception e) {
system.out.println(e.getmessage());
}
}
}
/**
* 关闭statement
* @param stmt
*/
public static void closestatement(statement stmt) {
if (stmt != null) {
try {
stmt.close();
}
catch (exception e) {
system.out.println(e.getmessage());
}
}
}
/**
* 关闭resultset、statement
* @param rs
* @param stmt
*/
public static void closestatement(resultset rs, statement stmt) {
closeresultset(rs);
closestatement(stmt);
}
/**
* 关闭preparedstatement
* @param pstmt
* @throws sqlexception
*/
public static void fastclosestmt(preparedstatement pstmt) throws sqlexception
{
pstmt.close();
}
/**
* 关闭resultset、preparedstatement
* @param rs
* @param pstmt
* @throws sqlexception
*/
public static void fastclosestmt(resultset rs, preparedstatement pstmt) throws sqlexception
{
rs.close();
pstmt.close();
}
/**
* 关闭resultset、statement、connection
* @param rs
* @param stmt
* @param con
*/
public static void closeconnection(resultset rs, statement stmt, connection con) {
closeresultset(rs);
closestatement(stmt);
closeconnection(con);
}
/**
* 关闭statement、connection
* @param stmt
* @param con
*/
public static void closeconnection(statement stmt, connection con) {
closestatement(stmt);
closeconnection(con);
}
/**
* 关闭connection
* @param con
*/
public static void closeconnection(connection con) {
if (con != null) {
try {
con.close();
}
catch (exception e) {
system.out.println(e.getmessage());
}
}
}
}
以上就是本文的全部内容了,希望对大家熟练掌握java能有所帮助。