JDBC连接与增删查改的封装

package dao;

import java.lang.reflect.Field;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Vector;

import model.Admin;

public class DbDao {
private static String db_driver = “com.mysql.jdbc.Driver”;//数据库驱动
private static String db_url = “jdbc:mysql://localhost:3306/wd?userUnicode=true&characterEncoding=utf-8”;//连接字符串
private static String db_userName = “root”;//用户名
private static String db_userPass = “123456”;//用户密码
private static String db_state = “”;//状态
private static String db_dataBaseName = “”;//数据库名

private static Connection conn = null;//连接对象
private static PreparedStatement pst = null;//预编译对象
private static CallableStatement cs= null;
public static ResultSet res = null;//结果集对象
private static Statement st = null; 

/**
 * 创建数据库连接
 * @return
 */
public static Connection getConn(){     
    try {
        Class.forName(db_driver);
        conn = java.sql.DriverManager.getConnection(db_url, db_userName, db_userPass);
        //conn.setAutoCommit(false);        //关闭自动提交功能,改为人工提交事务
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return conn;
}

/**
 * 关闭数据库参数
 */
public static void close(){
    try {
        if(res != null){
            res.close();
        }
        if(pst != null){
            pst.close();
        }
        if(st != null){
            st.close();
        }
        if(cs != null){
            cs.close();
        }
        if(conn != null){
            conn.close();
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
/*数据的增删改
 * 
 */

public int executeUpdate(String sql,Object…objects)throws SQLException{
//受影响行数
int lines=0;
conn=getConn();

  pst=conn.prepareStatement(sql);

  for(int i=0;i<objects.length;i++){

      pst.setObject(i+1, objects[i]);
  }
  lines=pst.executeUpdate();
 //lines=pst.executeUpdate();
  return lines;

}
/*
*增删改(带回滚操作)
* */
public int executeUpdateRB(String sql,Object…objects){
int rbLines=0;
conn=getConn();
try {
conn.setAutoCommit(false);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}//connection的默认提交方式是true
try{ pst=conn.prepareStatement(sql);
for(int i=0;i

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值