欢迎光临
我们一直在努力,专注IT互联网的资料分享

java中万能模板工具类SimpleDBUtil,实现增删改查功能

代码示例

package Tesst;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class SimpleDBUtil {

static final String DB_URL = “jdbc:mysql://localhost:3306/javamysqlproject?useUnicode=true&characterEncoding=utf8”;
static final String USER = “root”;
static final String PASS = “123456”;

/**
* Open Connection
* @return java.sql.Connection
*/
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName(“com.mysql.jdbc.Driver”);
conn = DriverManager.getConnection(DB_URL, USER, PASS);

} catch (Exception ex) {
ex.printStackTrace();
}
return conn;
}

/**
* 实现所有的添加,删除,修改
* @param sql
* @param params
* @return
*/
public static int executeUpdate(String sql, Object[] params){
Connection conn=null;
PreparedStatement pstmt=null;

try{
conn=getConnection();
pstmt=conn.prepareStatement(sql);

if(params !=null){
for(int i=0; i<params.length; i++){
pstmt.setObject(i+1, params[i]);
}
}
return pstmt.executeUpdate();
}catch(Exception ex){
ex.getStackTrace();
}finally{
closeAll(conn , pstmt, null);
}
return -1;
}

/**
* 实现万能查询方式
*/
public static ResultSet executeQuery(String sql, Object[] params){

Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;

try{
conn=getConnection();
pstmt=conn.prepareStatement(sql);

if(params !=null){
for(int i=0; i<params.length; i++){
pstmt.setObject(i+1, params[i]);
}
}
return rs=pstmt.executeQuery();

}catch(Exception ex){
ex.getStackTrace();
}finally{
//closeAll(conn , pstmt, rs);
}
return rs;
}

/**
* close and release resources
* @param conn
* @param pstmt
* @param rs
*/
public static void closeAll(Connection conn, PreparedStatement pstmt, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception ex) {
System.out.println(“An exception occurred while closing, ” + ex.getMessage());
}
}
}

赞(1) 打赏
未经允许不得转载:辰熙博客 » java中万能模板工具类SimpleDBUtil,实现增删改查功能
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏