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;
}
本文详细阐述了在SQL操作中使用预编译语句、批量处理参数以及事务管理等技术,以提高数据库交互效率和减少资源消耗。通过实例演示了如何通过优化SQL语句执行和结果集获取过程,实现对数据库操作的高效管理和资源利用。
6124

被折叠的 条评论
为什么被折叠?



