select转insert语句

备注:select查询出来的数据转成insert语句,可以直接执行SQL

 

package com.ed.core.util;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

import com.ed.core.domain.PProject;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;

public class CreateInsert {

	 private static Pattern linePattern = Pattern.compile("_(\\w)");
	
    /**
     * 生成插入语句
     * @param tablename 表明
     * @param clazz 与数据库中字段一一对应的类
     * @param t 有数据的实体
     * @param <T> 数据实体类型 如 User
     */
    public static  <T> String getInsertSql(String tablename, Class<T> clazz, T t){
        //insert into table_name (column_name1,column_name2, ...) values (value1,value2, ...)
        String sql = "";
        Field[] fields = ReflectUtil.getFieldsDirectly(clazz, false);
        StringBuffer topHalf = new StringBuffer("insert into "+tablename+" (");
        StringBuffer afterAalf = new StringBuffer("values (");
        for (Field field : fields) {
            /*if ("ID".equals(field.getName()) || "id".equals(field.getName())){
                continue;   //id 自动生成无需手动插入
            }*/
            topHalf.append(field.getName() + ",");
            if (ReflectUtil.getFieldValue(t, field.getName()) instanceof String) {
                afterAalf.append("'" + ReflectUtil.getFieldValue(t, field.getName()) + "',");
            } else {
                afterAalf.append(ReflectUtil.getFieldValue(t, field.getName()) + ",");
            }
        }
        topHalf = new StringBuffer(StrUtil.removeSuffix(topHalf.toString(), ","));
        afterAalf = new StringBuffer(StrUtil.removeSuffix(afterAalf.toString(), ","));
        topHalf.append(") ");
        afterAalf.append(") ");
        sql = topHalf.toString() + afterAalf.toString();
        return sql;
    }

    /**
     * 生成更新语句
     * 必须含有id
     * 数据实体中 null 与 空字段不参与更新
     * @param tablename 数据库中的表明
     * @param clazz 与数据库中字段一一对应的类
     * @param t 有数据的实体
     * @param <T> 数据实体类型,如 User
     */
    public static  <T> String getUpdateSql(String tablename, Class<T> clazz, T t){
        //UPDATE table_name SET column_name1 = value1, column_name2 = value2, ... where ID=xxx
        //or
        //UPDATE table_name SET column_name1 = value1, column_name2 = value2, ... where id=xxx
        String sql = "";
        String id = ""; //保存id名:ID or id
        Field[] fields = ReflectUtil.getFieldsDirectly(clazz, false);
        sql = "update "+tablename+" set ";
        for (Field field : fields) {
            StringBuffer tmp = new StringBuffer();
            if ("ID".equals(field.getName()) || "id".equals(field.getName())){
                id = field.getName();
                continue;//更新的时候无需set id=xxx
            }
            if (ReflectUtil.getFieldValue(t, field.getName()) != null && ReflectUtil.getFieldValue(t, field.getName()) != "") {
                tmp.append( field.getName() + "=");
                if (ReflectUtil.getFieldValue(t, field.getName()) instanceof String) {
                    tmp.append( "'" + ReflectUtil.getFieldValue(t, field.getName()) + "',");
                } else {
                    tmp.append(ReflectUtil.getFieldValue(t, field.getName()) + ",");
                }
                sql += tmp;
            }
        }
        sql = StrUtil.removeSuffix(sql, ",") + " where " + id + "='" + ReflectUtil.getFieldValue(t, id)+"'";
        return sql;
    }


    /**
     * //根据数据库生成字段 例如 private Object a;
     * @param dbname 数据库名
     * @param tablename 表名称
     * @return 成员变量拼接后的字符串
     * @throws SQLException
     */
    public static <T> String getPirvateObjectXxx(String dbname,String tablename, T t) throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException, ParseException {
        Class.forName("org.postgresql.Driver").newInstance();
        Connection conn = DriverManager.getConnection("jdbc:postgresql://xxx.xxx.x.xx:端口号/数据库名", "用户名", "密码");/*获取你的数据库连接*/;
        Statement stat = conn.createStatement();
        //select COLUMN_NAME from information_schema.columns where table_schema='public' and table_name='p_project';
//        ResultSet rs = stat.executeQuery("select COLUMN_NAME,COLUMN_TYPE from information_schema.COLUMNS where table_name = '"+tablename+"' and table_schema = '"+dbname+"'");
        ResultSet rs = stat.executeQuery("select COLUMN_NAME from information_schema.columns where table_schema='public' and table_name='"+tablename+"'");
        StringBuffer topHalf = new StringBuffer("insert into "+tablename+" (");
        StringBuffer afterAalf = new StringBuffer("values (");
        while (rs.next()) {
//            sb.append("private Object "+rs.getObject(1)+";\n");
        	
        	/*加上id是因为有些文件的路径通过id来拼接的路径
        	if(StringUtils.equals(rs.getObject(1).toString(), "id")) {
        		continue;
        	}*/
        	
        	topHalf.append(rs.getObject(1)+ ",");
//        	System.out.println("***"+rs.getObject(1));
        	
        	//只需要判断string类型和data类型,string类型需要加引号(''),时间需要转换并加引号
        	Field field = ReflectUtil.getField(t.getClass(), lineToHump(rs.getObject(1).toString()));
        	if (field.getGenericType().toString().equals("class java.lang.String")) {
        		afterAalf.append("'" + ReflectUtil.getFieldValue(t,lineToHump(rs.getObject(1).toString())) + "',");
        	}else if(field.getGenericType().toString().equals("class java.util.Date")){
                /**
                 * lineToHump(rs.getObject(1).toString() 获取bean里面的属性
                 * ReflectUtil.getFieldValue(t, lineToHump(rs.getObject(1).toString()))  根据bean里的属性获取具体的值
                 */
                Object fieldValue = ReflectUtil.getFieldValue(t, lineToHump(rs.getObject(1).toString()));
                if(fieldValue != null){
                    afterAalf.append("'" + CSTtoDate(fieldValue.toString()) + "',");
                }
            }else {
        		afterAalf.append(ReflectUtil.getFieldValue(t,lineToHump(rs.getObject(1).toString())) + ",");
        	}
        			                         
            //topHalf.append(rs.getObject(1)+";" + ",");
           /* if (ReflectUtil.getFieldValue(t, rs.getObject(1).toString()) instanceof String) {
                afterAalf.append("'" + ReflectUtil.getFieldValue(t,lineToHump(rs.getObject(1).toString())) + "',");
            } else {
                afterAalf.append(ReflectUtil.getFieldValue(t,lineToHump(rs.getObject(1).toString())) + ",");
            }*/
        }
        topHalf = new StringBuffer(StrUtil.removeSuffix(topHalf.toString(), ","));
        afterAalf = new StringBuffer(StrUtil.removeSuffix(afterAalf.toString(), ","));
        topHalf.append(") ");
        afterAalf.append(") ");
        String sql = topHalf.toString() + afterAalf.toString();
//        while (rs.next()) {
//            sb.append("private Object "+rs.getObject(1)+";\n");
//        }
//        System.out.print(sb.toString());
        rs.close();
        stat.close();
        conn.close();
//        return sb.toString();
        return sql;
    }

    getInsertSql生成insert语句测试
    public static void main(String[] args) throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException, ParseException {
       
    	//String result = lineToHump("project_id");
    	
    	PProject project= new PProject();
        project.setPeojectId(1);
        project.setProjectName("测试项目");
        project.setProjectCode("cs001");
        project.setProjectDescribe("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaa");
        project.setStatus(1);
        project.setCreateDate(new Date(System.currentTimeMillis()));

        String insertSql = getInsertSql("p_project", PProject.class, project);
        System.out.println(insertSql);
        String insertSqlDataBase = getPirvateObjectXxx("public", "p_project", project);
        //System.out.println(insertSql);
        System.out.println(insertSqlDataBase);

        System.out.println(CSTtoDate("Thu Feb 27 22:14:18 CST 2020"));
    }

    /**
     * 获取bean里面的属性
     * @param str
     * @return
     */
    public static String lineToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 时间转换
     * @param dateStr
     * @return
     * @throws ParseException
     */
    public static String CSTtoDate(String dateStr) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);

        Date date = (Date) sdf.parse(dateStr);

        String formatStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);

        return formatStr;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值