鱼C论坛

 找回密码
 立即注册
查看: 2816|回复: 0

[技术交流] 自己封装的JavaBean转化为sql

[复制链接]
发表于 2014-9-12 15:49:26 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. import java.lang.reflect.Field;
  2. import java.sql.Connection;
  3. import java.sql.PreparedStatement;
  4. import java.sql.SQLException;
  5. import java.util.Map;


  6. public class DatabaseUtil {
  7.         /**
  8.          *
  9.          * @param modelName 需要持久化的类名(类名需要和数据库表名一致)
  10.          * @param conn
  11.          * @param map 存储model里面的属性
  12.          * @return PreparedStatement
  13.          * @throws SQLException
  14.          * @throws SecurityException
  15.          * @throws ClassNotFoundException
  16.          */
  17.         public PreparedStatement CreateInsertSQL(String modelName,Connection conn ,Map<String, String[]> map) throws SQLException, SecurityException, ClassNotFoundException{
  18.                
  19.                 String sql = "insert into " + modelName.substring(modelName.lastIndexOf(".")+1)+"(";
  20.                 Field[] field = Class.forName(modelName).getDeclaredFields();
  21.                
  22.                 for(int i=0; i<field.length; i++){
  23.                         sql += field[i].getName()+",";
  24.                 }
  25.                 sql = sql.substring(0, sql.length()-1) + ") " + "values(";
  26.                
  27.                 for(int i=0; i<field.length; i++){
  28.                         sql += "?,";
  29.                 }
  30.                 sql = sql.substring(0, sql.length()-1) + ")";
  31.                 System.out.println(sql);
  32.                 PreparedStatement prepareStatement = conn.prepareStatement(sql);
  33.                 for(int i=0; i<field.length; i++){
  34.                         prepareStatement.setObject(i+1, filterParm(map.get(field[i].getName())));
  35.                 }
  36.                 return prepareStatement;
  37.         }
  38.         //过滤返回的NULL数组
  39.         public static String filterParm(String[] parm ){
  40.                 if(parm != null)
  41.                         return parm[0];
  42.                 return null;
  43.         }
  44. }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-3-29 13:48

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表