您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

JDBC操作技巧

2025/7/1 16:52:56发布29次查看
对于纯jdbc连接数据库连接工具如下: public static final string dbdriver=com.microsoft.sqlserver.jdbc.sqlserverdriver; public static final string dburl=jdbc:sqlserver://10.81.35.35:1433;databasename=company; public static final string dbuser
对于纯jdbc连接数据库连接工具如下:
public static final string dbdriver=com.microsoft.sqlserver.jdbc.sqlserverdriver; public static final string dburl=jdbc:sqlserver://10.81.35.35:1433;databasename=company; public static final string dbusernamw=sa; public static final string dbpsd=1111111; private connection conn=null; public databaseconnection(){ try{ class.forname(dbdriver); conn=drivermanager.getconnection(dburl,dbusernamw,dbpsd); }catch(exception e){ e.printstacktrace(); } } public connection getconnection(){ return this.conn ; } public void close() throws sqlexception{ if(this.conn!=null){ conn.close(); } }
然后我们便是采用preparedstatement对sql语句进行预处理,如下:preparedstatement pstm = null; string sql = insert into person(username,password) values(?,?); try { pstm = this.conn.preparestatement(sql); pstm.setstring(1, person.getusername()); pstm.setstring(2, person.getpassword()); int count = pstm.executeupdate(); if (count > 0) { flag = true; } } catch (exception e) { throw e; } finally { try { pstm.close(); } catch (exception e) { } }
这是我们最常用的一种操作方式,可是问题就来了,我们所要操作的,必须对sql中的字段很明确,比如我们按条件来查询的时候,我们就必须对条件的字段很清楚,可是,当数据库字段增多的时候,我们所要查询的条件规则很多,是不是每一个条件,我们就要写一个方法呢?显然,这种是直接的思维,然而这样思维却增加了很多代码的冗余,又或者说是,每次变换条件或者新增条件的时候,我们都必须对方法进行修改,甚至是增加。于是乎,我们想有没有一种方式可以传递字段名称进去查询,如where ?=?
本人亲测,这种方式是不存在的,因为预处理字段的时候,preparedstatement会自动在字符串上加引号,那此时就不能达到我们想要的效果(如想要的是where name=? 得到的却是 where 'name'=?),本人曾经在这样的问题上纠结了很久。最终找到一种破解的方式,这里借鉴了ibatis的map传参方式。希望同行爱好者,我们除了要学会使用框架或插件,得找个时间去研究一下它的原理(源码)哦。
对于where ?=? 显然是不可取,但是对于字符串占位就可以的。例子如下:
public list findbyparams(map params) throws exception { iterator it = params.entryset().iterator(); list list = new arraylist(); person person = null; string key = null; object value = null; preparedstatement pstm = null; while (it.hasnext()) { map.entry entry = (map.entry) it .next(); key = entry.getkey(); value = entry.getvalue(); } string sql = string.format( select userid,username,password from person where %s=?, key); pstm = this.conn.preparestatement(sql); pstm.setobject(1, value); resultset rs = pstm.executequery(); while(rs.next()) { person = new person(); person.setuserid(rs.getint(1)); person.setusername(rs.getstring(2)); person.setpassword(rs.getstring(3)); } rs.close(); pstm.close(); return list; }
哈哈 此种方式可以替代where ?=?,参照ibatis
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product