java中base包DBmanager直接面向 数据库的 详解

来源:互联网 发布:淘宝差评最多的店 编辑:程序博客网 时间:2024/05/22 22:59

1.

由于 不管是 得到 结果集 还是 几行受影响 

 都会 用到 几个 公共的 代码 和 变量 和 常量

           于是 提取出来  就是 

                       String  url="jdbc:sqlserver://localhost:1433;DataName=shopdb";

                          user="sa";

                          password="123456";

                           Connection sqlcon=null;

                            PreparedStatement pst=null;

又由于 每一个 都需要 加载 驱动类 和 产生 连接对象

 public static Connection getC(){

                 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

return DriverManager.getConnection(url,user,password);
}




1. update  detele insert 

  都只是 得到 有 几行受到 影响,

  public int  myexU(String sql , Object ... objs){

              sqlcon=getC();

             pst=sql.prepareStastement(sql);

              if(objs!=null){

                  int idext=1;  

              // 从1 开始的 赋值给 ---??? 占位符

                          for(object oo:objs){

                               pst.setObject(idext,oo); 

                               idext++;   

                          }

                }

                  int   iline = pst.executeUpdate();//执行sql语句并返回受影响的行数
return iline;

}

>>>>>>>>>>>>>>>>>>>>>>>>>>>

 对于 得到 的 是 结果集 的

 public Resultset mygetR(String sql , Object ... objs){

                 sqlcon=getC();

              Resultset cst=null;

           pst=sqlcon.prepareStatement(sql);

          if((objs!=null){

                 int idext=1;  

              // 从1 开始的 赋值给 ---??? 占位符

                          for(object oo:objs){

                               pst.setObject(idext,oo); 

                               idext++;   

                          }

           }

      cst=pst.executeQuery();  执行把值全给了 cst

   return rst;


             

}


——————————————————————————

3. 对于 有多条的 sql 语句的 执行 就需要 一个比较复杂的


public int Mytran(List<String> sqlList,List<object[]> objsList ){

          int  inline=-1;

          sqlcon=getC();

          sqlcon.setAutoCommit(false);

   - - - - - - - - - - - - -- - - - -- - - - - -- - - - 

            for(int i=0;i<sqlList.size();i++)

                {  

                 String sql=sqlList.get(i);

                Object [] objs=objsList.get(i);//获取要执行的sql语句的参数
pst=sqlcon.prepareStatement(sql);//创建pst对象

  if(objsList!=null){if(objs.length>0){int idx=1;

                              for(Object obj : objs){pst.setObject(idx, obj);

idx++;
        }
                              } 

                          }

               pst.execute();//执行sql语句

                 }

                iline=1;
sqlcon.commit();

   以上是包含在  try 中的

                    catch(){

                                 sqlcon.rollback();

                               }

 return  inline;

}


0 0
原创粉丝点击