zoukankan      html  css  js  c++  java
  • 数据访问层

    public class BaseDao {

    //数据库驱动字符串

    private String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";

    //链接url字符串

    private String url="jdbc:sqlserver://localhost:1433;databaseName=My";

    //数据库用户名
    private String user="sa";

    //用户密码
    private String password="";

    //数据库链接对象

    Connection con=null;


    Statement stmt=null;

    //结果集对象
    ResultSet rs=null;

     //获取数据库连接对象

    public Connection getConnection(){
    if(con==null){

    //获取链接并捕捉异常
    try{
    Class.forName(driver);//加载jdbc驱动
    con=DriverManager.getConnection(url,user,password);
    }catch(Exception e){
    e.printStackTrace();//异常处理
    }
    }

    return con;//返回连接对象
    }

    //关闭数据库连接

    public void closeAll(Connection con,Statement stmt,ResultSet rs){
    try{
    if(rs!=null){//若结果集不为空
    rs.close();//关闭结果集
    }
    if(stmt!=null){//若Statemet对象不为空
    stmt.close();//关闭Statement对象
    }
    if(con!=null){//若链接对象不为空
    con.close();//关闭链接对象
    }
    }catch(Exception e){
    e.printStackTrace();//异常处理
    }
    }

    //增删改的操作

    public int exceuteUpdate(String preparedSql,Object...param){
    PreparedStatement ps=null;
    int num=0;
    con=getConnection();
    try{
    ps=con.prepareStatement(preparedSql);
    if(param!=null){
    for (int i = 0; i < param.length; i++) {

    //为预编译sql设置参数
    ps.setObject(i+1, param[i]);
    }
    }
    num=ps.executeUpdate();
    }catch(SQLException e){
    e.printStackTrace();
    }finally{
    closeAll(con,ps,null);
    }
    return num;
    }

    public int exceuteSelect(String preparedSql,Object...param){
    PreparedStatement ps=null;
    int num=0;
    con=getConnection();
    try{
    ps=con.prepareStatement(preparedSql);
    if(param.length>0){
    for (int i = 0; i < param.length; i++) {
    ps.setObject(i+1, param[i]);
    }
    }
    num=ps.executeUpdate();
    }catch(SQLException e){
    e.printStackTrace();
    }finally{
    closeAll(con,ps,null);
    }
    return num;
    }


    }

  • 相关阅读:
    Linux I2C设备驱动编写(一)
    Device Tree常用方法解析
    Linux查看CPU型号及内存频率及其它信息的命令
    编译错误error: invalid storage class
    Mysql技术内幕——表&索引算法和锁
    mysql 锁
    MySQL 索引方式
    通过show status 来优化MySQL数据库
    linux shell 字符串操作(长度,查找,替换)详解
    bash中将字符串split成数组的方法
  • 原文地址:https://www.cnblogs.com/with-lj/p/6726506.html
Copyright © 2011-2022 走看看