|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- import java.lang.reflect.Field;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.SQLException;
- import java.util.Map;
- public class DatabaseUtil {
- /**
- *
- * @param modelName 需要持久化的类名(类名需要和数据库表名一致)
- * @param conn
- * @param map 存储model里面的属性
- * @return PreparedStatement
- * @throws SQLException
- * @throws SecurityException
- * @throws ClassNotFoundException
- */
- public PreparedStatement CreateInsertSQL(String modelName,Connection conn ,Map<String, String[]> map) throws SQLException, SecurityException, ClassNotFoundException{
-
- String sql = "insert into " + modelName.substring(modelName.lastIndexOf(".")+1)+"(";
- Field[] field = Class.forName(modelName).getDeclaredFields();
-
- for(int i=0; i<field.length; i++){
- sql += field[i].getName()+",";
- }
- sql = sql.substring(0, sql.length()-1) + ") " + "values(";
-
- for(int i=0; i<field.length; i++){
- sql += "?,";
- }
- sql = sql.substring(0, sql.length()-1) + ")";
- System.out.println(sql);
- PreparedStatement prepareStatement = conn.prepareStatement(sql);
- for(int i=0; i<field.length; i++){
- prepareStatement.setObject(i+1, filterParm(map.get(field[i].getName())));
- }
- return prepareStatement;
- }
- //过滤返回的NULL数组
- public static String filterParm(String[] parm ){
- if(parm != null)
- return parm[0];
- return null;
- }
- }
复制代码 |
|