java 反射创建对象并赋值_[原创] Java JDBC连接数据库,反射创建实体类对象并赋值数据库行记录(支持存储过程)...

1 import java.lang.reflect.*;2 import java.sql.*;3 import java.util.*;4

5 public classSqlHelper {6 //SQL Server

7 /**

8 * JDBC驱动名称9 */

10 public static final String CLASS_NAME = "com.microsoft.sqlserver.jdbc.SQLServerDriver";11 /**

12 * 数据库连库字符串13 */

14 public static final String URL = "jdbc:sqlserver://192.168.1.254:1433;databaseName=BBSDB";15 /**

16 * 用户名17 */

18 public static final String UID = "sa";19 /**

20 * 密码21 */

22 public static final String PWD = "";23 /**

24 * JDBC驱动类型25 */

26 public static Class CLS = null;27

28 //Oracle29 //public static final String CLASS_NAME =30 //"oracle.jdbc.driver.OracleDriver";31 //public static final String URL =32 //"jdbc:oracle:thin:@localhost:1522:accp11g";33 //public static final String UID = "system";34 //public static final String PWD = "manager";

35 /**

36 * 获取数据库连接对象37 *38 *@return

39 *@throwsClassNotFoundException40 *@throwsSQLException41 */

42 public static Connection getConnection() throwsClassNotFoundException,43 SQLException {44 if (CLS == null) {45 CLS =Class.forName(CLASS_NAME);46 }47 returnDriverManager.getConnection(URL, UID, PWD);48 }49

50 /**

51 * 执行SQL语句不返回查询的操作,返回受影响的行数52 *53 *@paramsql54 * SQL语句55 *@return受影响的行数56 *@throwsClassNotFoundException57 *@throwsSQLException58 */

59 public static intexecuteNonQuery(String sql) {60 int result = -1;61 Connection con = null;62 PreparedStatement ps = null;63 try{64 con =getConnection();65 ps =con.prepareStatement(sql);66 result =ps.executeUpdate();67 } catch(Exception e) {68 e.printStackTrace();69 } finally{70 close(con, ps, null);71 }72 returnresult;73 }74

75 /**

76 * 执行Insert语句,返回Insert成功之后标识列的值77 *78 *@paramsql79 *@return

80 *@throwsClassNotFoundException81 *@throwsSQLException82 */

83 public static intexecuteIdentity(String sql) {84 int identity = -1;85 Connection con = null;86 Statement ps = null;87 ResultSet rs = null;88 try{89 con =getConnection();90 ps =con.createStatement();91 ps.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);92 rs =ps.getGeneratedKeys();93 if(rs.next()) {94 //identity = rs.getInt("GENERATED_KEYS");

95 identity = rs.getInt(1);96 }97 } catch(Exception e) {98 e.printStackTrace();99 } finally{100 close(con, ps, null);101 }102 returnidentity;103 }104

105 /**

106 * 执行不返回结果集的存储过程107 *108 *@paramsql109 * 存储过程名称110 *@paramparams111 * 存储过程参数112 *@throwsClassNotFoundException113 *@throwsSQLException114 */

115 public static voidexecuteNonQuery(String sql, SqlParameter... params) {116 Connection con = null;117 CallableStatement cs = null;118 try{119 con =getConnection();120 cs =con.prepareCall(sql);121 setSqlParameter(cs, params);122 cs.executeUpdate();123 getSqlParameter(cs, params);124 } catch(Exception e) {125 e.printStackTrace();126 } finally{127 close(con, cs, null);128 }129 }130

131 /**

132 * 执行返回聚合函数的操作133 *134 *@paramsql135 * 含有聚合函数的SQL语句136 *@return聚合函数的执行结果137 *@throwsSQLException138 *@throwsClassNotFoundException139 */

140 public static intexecuteScalar(String sql) {141 int result = -1;142 Connection con = null;143 PreparedStatement ps = null;144 ResultSet rs = null;145 try{146 con =getConnection();147 ps =con.prepareStatement(sql);148 rs =ps.executeQuery();149 if(rs.next()) {150 result = rs.getInt(1);151 }152 } catch(Exception e) {153 e.printStackTrace();154 } finally{155 close(con, ps, rs);156 }157 returnresult;158 }159

160 /**

161 * 执行返回泛型集合的SQL语句162 *163 *@paramcls164 * 泛型类型165 *@paramsql166 * 查询SQL语句167 *@return泛型集合168 *@throwsClassNotFoundException169 *@throwsSQLException170 *@throwsInstantiationException171 *@throwsIllegalAccessException172 */

173 public static List executeList(Classcls, String sql) {174 List list = new ArrayList();175 Connection con = null;176 PreparedStatement ps = null;177 ResultSet rs = null;178 try{179 con =getConnection();180 ps =con.prepareStatement(sql);181 rs =ps.executeQuery();182 while(rs.next()) {183 T obj =executeResultSet(cls, rs);184 list.add(obj);185 }186 } catch(Exception e) {187 e.printStackTrace();188 } finally{189 close(con, ps, rs);190 }191 returnlist;192 }193

194 /**

195 * 执行返回泛型集合的存储过程196 *197 *@paramcls198 * 泛型类型199 *@paramsql200 * 存储过程名称201 *@paramparams202 * 存储过程参数203 *@return泛型集合204 *@throwsClassNotFoundException205 *@throwsSQLException206 *@throwsInstantiationException207 *@throwsIllegalAccessException208 */

209 public static List executeList(Classcls, String sql,210 SqlParameter... params) {211 List list = new ArrayList();212 Connection con = null;213 CallableStatement cs = null;214 ResultSet rs = null;215 try{216 con =getConnection();217 cs =con.prepareCall(sql);218 setSqlParameter(cs, params);219 rs =cs.executeQuery();220 while(rs.next()) {221 T obj =executeResultSet(cls, rs);222 list.add(obj);223 }224 } catch(Exception e) {225 e.printStackTrace();226 } finally{227 close(con, cs, rs);228 }229 returnlist;230 }231

232 /**

233 * 执行返回泛型类型对象的SQL语句234 *235 *@paramcls236 * 泛型类型237 *@paramsql238 * SQL语句239 *@return泛型类型对象240 *@throwsSQLException241 *@throwsClassNotFoundException242 *@throwsInstantiationException243 *@throwsIllegalAccessException244 */

245 public static T executeEntity(Classcls, String sql) {246 T obj = null;247 Connection con = null;248 PreparedStatement ps = null;249 ResultSet rs = null;250 try{251 con =getConnection();252 ps =con.prepareStatement(sql);253 rs =ps.executeQuery();254 while(rs.next()) {255 obj =executeResultSet(cls, rs);256 break;257 }258 } catch(Exception e) {259 e.printStackTrace();260 } finally{261 close(con, ps, rs);262 }263 returnobj;264 }265

266 /**

267 * 执行返回泛型类型对象的存储过程268 *269 *@paramcls270 * 泛型类型271 *@paramsql272 * SQL语句273 *@paramparams274 * 存储过程参数275 *@return泛型类型对象276 *@throwsSQLException277 *@throwsClassNotFoundException278 *@throwsInstantiationException279 *@throwsIllegalAccessException280 */

281 public static T executeEntity(Classcls, String sql,282 SqlParameter... params) {283 T obj = null;284 Connection con = null;285 CallableStatement cs = null;286 ResultSet rs = null;287 try{288 con =getConnection();289 cs =con.prepareCall(sql);290 setSqlParameter(cs, params);291 rs =cs.executeQuery();292 while(rs.next()) {293 obj =executeResultSet(cls, rs);294 break;295 }296 } catch(Exception e) {297 e.printStackTrace();298 } finally{299 close(con, cs, rs);300 }301 returnobj;302 }303

304 /**

305 * 将一条记录转成一个对象306 *307 *@paramcls308 * 泛型类型309 *@paramrs310 * ResultSet对象311 *@return泛型类型对象312 *@throwsInstantiationException313 *@throwsIllegalAccessException314 *@throwsSQLException315 */

316 private static T executeResultSet(Classcls, ResultSet rs)317 throwsInstantiationException, IllegalAccessException, SQLException {318 T obj =cls.newInstance();319 ResultSetMetaData rsm =rs.getMetaData();320 int columnCount =rsm.getColumnCount();321 //Field[] fields = cls.getFields();

322 Field[] fields =cls.getDeclaredFields();323 for (int i = 0; i < fields.length; i++) {324 Field field =fields[i];325 String fieldName =field.getName();326 for (int j = 1; j <= columnCount; j++) {327 String columnName =rsm.getColumnName(j);328 if(fieldName.equalsIgnoreCase(columnName)) {329 Object value =rs.getObject(j);330 field.setAccessible(true);331 field.set(obj, value);332 break;333 }334 }335 }336 returnobj;337 }338

339 /**

340 * 设置存储过程参数名称,参数值,参数方向341 *342 *@paramcs343 *@paramparams344 *@throwsSQLException345 */

346 private static voidsetSqlParameter(CallableStatement cs,347 SqlParameter... params) throwsSQLException {348 if (params != null) {349 for(SqlParameter param : params) {350 if(param.OutPut) {351 String paramName =param.Name;352 if (paramName == null || paramName.equals("")) {353 cs.registerOutParameter(1, param.Type);//设置返回类型参数

354 } else{355 cs.registerOutParameter(paramName, param.Type);//设置输出类型参数

356 }357 } else{358 cs.setObject(param.Name, param.Value);//设置输入类型参数

359 }360 }361 }362 }363

364 /**

365 * 得到存储过程参数执行结果366 *367 *@paramcs368 *@paramparams369 *@throwsSQLException370 */

371 private static voidgetSqlParameter(CallableStatement cs,372 SqlParameter... params) throwsSQLException {373 for(SqlParameter param : params) {374 if(param.OutPut) {375 String paramName =param.Name;376 if (paramName == null || paramName.equals("")) {377 param.Value = cs.getObject(1);//返回类型参数值

378 } else{379 param.Value = cs.getObject(paramName);//输出类型参数值

380 }381 }382 }383 }384

385 /**

386 * 关闭JDBC对象,释放资源。387 *388 *@paramcon389 * 连接对象390 *@paramps391 * 命令对象392 *@paramrs393 * 结果集对象394 *@throwsSQLException395 */

396 private static voidclose(Connection con, Statement ps, ResultSet rs) {397 try{398 rs.close();399 if (rs != null) {400

401 rs = null;402 }403 if (ps != null) {404 ps.close();405 ps = null;406 }407 if (con != null) {408 con.close();409 con = null;410 }411 } catch(SQLException e) {412 //TODO Auto-generated catch block

413 e.printStackTrace();414 }415 }416 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值