1. 程式人生 > >Java Bean檔案例項生成資料庫

Java Bean檔案例項生成資料庫

package com.mc;
import java.io.File;
import java.io.FileReader;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 *
 * DB_URL 資料庫url 注:應以'/'結尾 而且不應該帶資料庫名
 * DATABASE 資料庫名
 * IS_CREATE_DATABASE 是否建立資料庫 如果true且資料庫存在會發生Exception異常
 * USER 賬號
 * PASS 密碼
 * FILE_PATH 要生成資料庫表的Bean檔案所在的資料夾
 *
 * @author mc
 *
 */
public class Instance {
 
    private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    private static final String DB_URL = "jdbc:mysql://localhost/";
    private static final String DATABASE = "room111";
    private static final boolean IS_CREATE_DATABASE = true;
    private static final String USER = "root";
    private static final String PASS = "room";
    private static final String FILE_PATH = "C:\\Users\\mc\\Desktop\\appweb\\src\\main\\java\\com\\pojo";
    private static StringBuffer sb = new StringBuffer();
    private static Map<String, List<String[]>> map = new HashMap();
    private static int index;
    /**
     * change方法用以後面擴充套件
     * @param s 接收的bean檔案 屬性型別
     * @return 資料庫要建立的型別
     */
    public static String change(String s){
        switch (s){
            case "long":
            case "Long":
                s = "BIGINT";
                break;
            case "String":
            case "BigDecimal":
                s = "VARCHAR(255)";
                break;
        }
        return s;
    }
 
    public static void main(String[] args) throws Exception {
        Class.forName(JDBC_DRIVER);
        if(IS_CREATE_DATABASE){
            String sql = "create database "+DATABASE+" character set utf8 collate utf8_general_ci";
            if(!executeUpdate(DB_URL, sql)){
                System.err.println("建立資料庫失敗.");
                throw new Exception();
            }
        }
 
        File file = new File(FILE_PATH);
        File[] files = file.listFiles();
        int ch;
        for (File f : files) {
            if(f.isFile() && f.getName().endsWith(".java")){
                FileReader fileReader = new FileReader(f);
                sb.delete(0,sb.length());
                index = 0;
                while ((ch=fileReader.read())!=-1){
                    sb.append((char)ch);
                }
                try {
                    jx();
                } catch (Exception e){
                    System.err.println("檔案:"+f.getName()+"不是Bean");
                }
 
                fileReader.close();
            }
        }
 
        for (String s : map.keySet()) {
            String sql = createSQL(s);
            if(!executeUpdate(DB_URL+DATABASE,sql)){
                System.err.println("建立"+s+"表失敗:"+sql);
            }
        }
 
 
    }
 
    /**
     * createSQL 方法為生成資料庫的建表語句 可以根據需要修改
     * @param s 資料表名
     * @return 建立資料表的SQL語句
     */
    public static String createSQL(String s){
        String sql = "CREATE TABLE "+s+" (";
        List<String[]> list = map.get(s);
        String[] id = deleteId(list);
        sql += id[1]+" "+id[0]+" not NULL,";
        for (String[] strs : list) {
            sql +=strs[1]+" "+strs[0]+",";
        }
 
        sql += "PRIMARY KEY ( "+id[1]+" )";
        sql+= ")";
        return sql;
    }
 
    public static String[] deleteId(List<String[]> list){
        for (int i=0;i<list.size();i++) {
            if(list.get(i)[1].equalsIgnoreCase("id")){
                return list.remove(i);
            }
        }
        return list.remove(0);
    }
 
    public static void jx() throws Exception {
        String table = jxStr("public class ", " ", null);
        if(table!=null){
            ArrayList<String[]> list = new ArrayList<>();
            String str;
            while ((str=jxStr("private ", ";", "class "))!=null){
                str = removeRedundantSpaces(str);
                String[] split = str.split(" ");
                if(split.length==2){
                    list.add(new String[]{change(split[0]), split[1]});
                }
            }
            map.put(removeRedundantSpaces(table), list);
        }
    }
 
    public static String removeRedundantSpaces(String s){
        s = s.trim();
        return s.replaceAll("\\s+", " ");
    }
 
    public static String jxStr(String startStr, String endStr, String abnormal) throws Exception {
        String str = sb.toString();
        if(abnormal!=null && str.indexOf(abnormal, index)!=-1){
            throw new Exception();
        }
        int i = str.indexOf(startStr, index);
        if(i!=-1){
            int i1 = str.indexOf(endStr, i+startStr.length());
            if(i1!=-1){
                index = i1+endStr.length();
                return str.substring(i + startStr.length(), i1);
            }
        }
        return null;
    }
 
    public static boolean executeUpdate(String dbUrl,String sql) {
        Connection conn = null;
        Statement stmt = null;
        try {
            conn = DriverManager.getConnection(dbUrl, USER, PASS);
            stmt = conn.createStatement();
            stmt.executeUpdate(sql);
        } catch (Exception e) {
            return false;
        }finally {
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(stmt!=null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }
 
}