• 数据访问层


    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;
    }


    }

  • 相关阅读:
    MySQL日志
    MySQL索引和事务
    【收集】腾讯AlloyTeam
    js基础知识点(只有点)
    【扩展】Canvas绘制列表的尝试
    开播 开博 凯博
    【总结】移动web问题小结
    〖前端开发〗HTML/CSS基础知识学习笔记
    第四次读书笔记——《代码大全》(续)
    C++笔记(1)
  • 原文地址:https://www.cnblogs.com/with-lj/p/6726506.html
Copyright © 2020-2023  润新知