DBCONN

时间:2023-03-09 01:54:43
DBCONN

package Ulike_servlet; //将该类保存到com.tools包中
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 DbConn {
protected PreparedStatement pstm;// 预编译sql
public Connection conn; // 声明Connection对象的实例
public Statement stmt; // 声明Statement对象的实例
public ResultSet rs; // 声明ResultSet对象的实例
private static String dbClassName;// 定义保存数据库驱动的变量
private static String dbUrl;
private static String dbUser;
private static String dbPwd;
public DbConn() { // 定义构造方法
try { // 捕捉异常
dbClassName = "com.mysql.jdbc.Driver"; // 获取数据库驱动
dbUrl = "jdbc:mysql://localhost:3306/btmdb?useUnicode=true&characterEncoding=utf-8"; // 获取URL
dbUser = "root"; // 获取登录用户
dbPwd = "0118"; // 获取密码
} catch (Exception e) {
e.printStackTrace(); // 输出异常信息
}
}

//获取数据库连接
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName(dbClassName).newInstance();
conn = DriverManager.getConnection(dbUrl, dbUser, dbPwd);
} catch (Exception ee) {
ee.printStackTrace();
}
if (conn == null) {
System.err
.println("警告: DBConnectionManager.getConnection() 获得数据库链接失败.\r\n\r\n链接类型:"
+ dbClassName
+ "\r\n链接位置:"
+ dbUrl
+ "\r\n用户/密码"
+ dbUser + "/" + dbPwd);
}
return conn;
}

/*
* 功能:关闭数据库的连接
*/
protected void closeAll() {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstm != null) {
try {
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
try {
if (conn != null && conn.isClosed() == false) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 执行sql语句
* */
public int executeSQL(String sql, Object[] param) throws Exception {
int rows = 0;
try {
conn=getConnection();
if (param != null && param.length > 0) {
pstm = conn.prepareStatement(sql);
for (int i = 0; i < param.length; i++) {
pstm.setString(i + 1, param[i].toString());
}
rows = pstm.executeUpdate();
} else {
stmt = conn.createStatement();
rows = stmt.executeUpdate(sql);
}
} finally {
this.closeAll();
}
System.out.println("处理成功!!");
return rows;
}
/**
* 查询sql语句
* */
protected ResultSet executeQuery(String sql, Object[] param) throws Exception {
try {
conn=getConnection();
if (param != null && param.length > 0) {
pstm = conn.prepareStatement(sql);
for (int i = 0; i < param.length; i++) {
pstm.setString(i + 1, param[i].toString());
}
rs = pstm.executeQuery();
} else {
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
}
} finally {

}
System.out.println("处理成功!!");
return rs;
}

}