資料庫表到java類轉換工具__資料庫

來源:互聯網
上載者:User
//該工具類可以實現:給定一個指定的資料庫表名,即可自動產生對應的java實體類
package com.iamzken.utils;import java.io.BufferedWriter;import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.net.URL;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;import java.util.Vector;public class DB2JavaConvertor {private Connection connection;private PreparedStatement UserQuery;/*mysql url的連接字串*/private static String url = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useOldAliasMetadataBehavior=true";//帳號private static String user = "root";//密碼private static String password = "";private Vector<String> vector = new Vector<String>();//mysql jdbc的java包驅動字串private String driverClassName = "com.mysql.jdbc.Driver";//資料庫中的表名String table = "teacher";//資料庫的列名稱private String[] colnames; // 列名數組//列名類型數組  private String[] colTypes;public DB2JavaConvertor(){try {//驅動註冊Class.forName(driverClassName);if (connection == null || connection.isClosed())//獲得連結connection = DriverManager.getConnection(url, user, password);} catch (ClassNotFoundException ex) {ex.printStackTrace();System.out.println("Oh,not");} catch (SQLException e) {e.printStackTrace();System.out.println("Oh,not");}}public Connection getConnection() {return connection;}public void setConnection(Connection connection) {this.connection = connection;}public void doAction(){String sql = "select * from "+table;try {PreparedStatement statement = connection.prepareStatement(sql);//擷取資料庫的中繼資料 ResultSetMetaData metadata = statement.getMetaData();//資料庫的欄位個數int len = metadata.getColumnCount();//欄位名稱colnames = new String[len+1];//欄位類型 --->已經轉化為java中的類名稱了colTypes = new String[len+1];for(int i= 1;i<=len;i++){//System.out.println(metadata.getColumnName(i)+":"+metadata.getColumnTypeName(i)+":"+sqlType2JavaType(metadata.getColumnTypeName(i).toLowerCase())+":"+metadata.getColumnDisplaySize(i));//metadata.getColumnDisplaySize(i);colnames[i] = metadata.getColumnName(i); //擷取欄位名稱colTypes[i] = sqlType2JavaType(metadata.getColumnTypeName(i)); //擷取欄位類型}} catch (SQLException e) {e.printStackTrace();}}/* * mysql的欄位類型轉化為java的類型*/private String sqlType2JavaType(String sqlType) {                  if(sqlType.equalsIgnoreCase("bit")){              return "boolean";          }else if(sqlType.equalsIgnoreCase("tinyint")){              return "byte";          }else if(sqlType.equalsIgnoreCase("smallint")){              return "short";          }else if(sqlType.equalsIgnoreCase("INTEGER")){              return "int";          }else if(sqlType.equalsIgnoreCase("bigint")){              return "long";          }else if(sqlType.equalsIgnoreCase("float")){              return "float";          }else if(sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("numeric")                   || sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money")                   || sqlType.equalsIgnoreCase("smallmoney")){              return "double";          }else if(sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char")                   || sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar")                   || sqlType.equalsIgnoreCase("text")){              return "String";          }else if(sqlType.equalsIgnoreCase("datetime") ||sqlType.equalsIgnoreCase("date")){              return "java.util.Date";          }else if(sqlType.equalsIgnoreCase("image")){              return "Blod";          }                    return null;      }/*擷取整個類的字串並且輸出為java檔案 * */public  StringBuffer getClassStr(){String className = table.substring(0,1).toUpperCase()+table.substring(1);//輸出的類字串StringBuffer str = new StringBuffer("");//擷取表類型和表名的欄位名this.doAction();//校正if(null == colnames && null == colTypes) return null;str.append(this.getClass().getPackage()+";\r\n\r\n");//拼接str.append("public class "+className+" {\r\n");//拼接屬性for(int index=1; index < colnames.length ; index++){str.append(getAttrbuteString(colnames[index],colTypes[index]));}//拼接get,Set方法for(int index=1; index < colnames.length ; index++){str.append(getGetMethodString(colnames[index],colTypes[index]));str.append(getSetMethodString(colnames[index],colTypes[index]));}str.append("}\r\n");//輸出到檔案中String s1 = DB2JavaConvertor.class.getPackage().getName().replace(".", "\\");String s2 = "src"+File.separator+"main"+File.separator+"java"+File.separator+s1;String s3 =   System.getProperty("user.dir")+File.separator+s2;  File file = new File(s3);if(!file.exists()){file.mkdirs();}BufferedWriter write = null;try {write = new BufferedWriter(new FileWriter(new File(s3+File.separator+className+".java")));write.write(str.toString());write.close();} catch (IOException e) {e.printStackTrace();if (write != null)try {write.close();} catch (IOException e1) {e1.printStackTrace();}}return str;}/* * 擷取欄位字串*/public StringBuffer getAttrbuteString(String name, String type) {if(!check(name,type)) {System.out.println("類中有屬性或者類型為空白");return null;};String format = String.format("    private %s %s;\n\r", new String[]{type,name});return new StringBuffer(format);}/* * 校正name和type是否合法*/public boolean check(String name, String type) {if("".equals(name) || name == null || name.trim().length() ==0){return false;}if("".equals(type) || type == null || type.trim().length() ==0){return false;}return true;}/* * 擷取get方法字串*/private StringBuffer getGetMethodString(String name, String type) {if(!check(name,type)) {System.out.println("類中有屬性或者類型為空白");return null;};String Methodname = "get"+GetTuoFeng(name);String format = String.format("    public %s %s(){\n\r", new Object[]{type,Methodname});format += String.format("        return this.%s;\r\n", new Object[]{name});format += "    }\r\n";return new StringBuffer(format);}//將名稱首字元大寫private String GetTuoFeng(String name) {name = name.trim();if(name.length() > 1){name = name.substring(0, 1).toUpperCase()+name.substring(1);}else{name = name.toUpperCase();}return name;}/* * 擷取欄位的get方法字串*/private Object getSetMethodString(String name, String type) {if(!check(name,type)) {System.out.println("類中有屬性或者類型為空白");return null;};String Methodname = "set"+GetTuoFeng(name);String format = String.format("    public void %s(%s %s){\n\r", new Object[]{Methodname,type,name});format += String.format("        this.%s = %s;\r\n", new Object[]{name,name});format += "    }\r\n";return new StringBuffer(format);}public static void main(String[] args) throws IOException {DB2JavaConvertor bean = new DB2JavaConvertor();System.err.println(bean.getClassStr());//System.out.println(ReflectBean.class.getPackage());//System.out.println(ReflectBean.class.getPackage().getName());//System.out.println(ReflectBean.class.getResource("").getPath());//File directory = new File("");//參數為空白 //String courseFile = directory.getCanonicalPath() ; //System.out.println(courseFile); //////File f = new File(ReflectBean.class.getResource("").getPath()); //System.out.println(f);//////URL xmlpath = ReflectBean.class.getClassLoader().getResource(""); //System.out.println(xmlpath);////String s1 = directory.getAbsolutePath();//System.out.println(s1);/*String s3 = ReflectBean.class.getPackage().getName().replace(".", "\\");String s2 =   System.getProperty("user.dir")+File.separator+s3;  System.out.println(s2);*/}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.