【MapSheep】
[好记性不如烂笔头]
posts - 228,comments - 15,views - 17万
package com.xcgdt.template;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mysql.jdbc.Driver;
public class BaseDao {
private static String drive_class = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/train?useUnicode=true&characterEncoding=utf-8";
private static String user = "root";
private static String password = "shell_girl";
//加载驱动
static {
try {
Class.forName(drive_class);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 连接数据库
*
* @param sql
* @return
*/
public Connection getConnection() {
try {
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 执行增删改
*
* @param sql
* @param pramas
* @return
*/
public ResultSet executeQuery(String sql, Object... pramas) {
Connection conn = this.getConnection();
PreparedStatement stmt = null;
try {
stmt = conn.prepareStatement(sql);
if (pramas != null && pramas.length != 0) {
for (int i = 0; i < pramas.length; i++) {
stmt.setObject(i + 1, pramas[i]);
}
}
ResultSet rs = stmt.executeQuery();
return rs;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 执行增删改
*
* @param sql
* @param pramas
* @return
*/
public int executeUpdate(String sql, Object... pramas) {
Connection conn = this.getConnection();
PreparedStatement pstmt = null;
try {
int result = 0;
pstmt = conn.prepareStatement(sql);
if (pramas != null && pramas.length != 0) {
for (int i = 0; i < pramas.length; i++) {
pstmt.setObject(i + 1, pramas[i]);
}
}
result = pstmt.executeUpdate();
return result;
} catch (SQLException e) {
e.printStackTrace();
} finally {
this.closeAll(pstmt, null, conn);
}
return 0;
}
/**
* 释放资源
*
* @param stmt
* @param rs
* @param conn
*/
public void closeAll(Statement stmt, ResultSet rs, Connection conn) {
try {
if (stmt != null) {
stmt.close();
stmt = null;
}
if (rs != null) {
rs.close();
rs = null;
}
if (conn != null && conn.isClosed() == false) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
posted on   (Play)  阅读(57)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~

点击右上角即可分享
微信分享提示