根据数据库表结构生成java类

  1 import java.io.File;
  2 import java.io.FileWriter;
  3 import java.io.IOException;
  4 import java.io.PrintWriter;
  5 import java.sql.Connection;
  6 import java.sql.DatabaseMetaData;
  7 import java.sql.PreparedStatement;
  8 import java.sql.ResultSet;
  9 import java.sql.ResultSetMetaData;
 10 import java.sql.SQLException;
 11 import java.util.ArrayList;
 12 import java.util.List;
 13  
 14 import android.ConnectionFactory;
 15  
 16 /**
 17  * 根据数据库表 生成java 实体类
 18  *
 19  * @author DLHT
 20  * @time 2015年9月29日下午4:13:42
 21  * @className GenEntityTool.java
 22  */
 23 public class GenEntityTool {
 24     private String tablename = "test";
 25  
 26     private String[] colnames; // 列名数组
 27  
 28     private String[] colTypes; // 列名类型数组
 29  
 30     private int[] colSizes; // 列名大小数组
 31  
 32     private boolean f_util = false; // 是否需要导入包java.util.*
 33  
 34     private boolean f_sql = false; // 是否需要导入包java.sql.*
 35  
 36     public GenEntityTool() {
 37  
 38         getTablesName();
 39  
 40  
 41         Connection conn = null;
 42         PreparedStatement pstmt = null;
 43         ResultSetMetaData rsmd = null;
 44  
 45         conn = ConnectionFactory.getInstance().getConnection();
 46         String strsql = "select * from " + tablename;
 47         try {
 48             pstmt = conn.prepareStatement(strsql);
 49             rsmd = pstmt.getMetaData();
 50             int size = rsmd.getColumnCount(); // 共有多少列
 51             colnames = new String[size];
 52             colTypes = new String[size];
 53             colSizes = new int[size];
 54             for (int i = 0; i < rsmd.getColumnCount(); i++) {
 55                 colnames[i] = rsmd.getColumnName(i + 1);
 56                 colTypes[i] = rsmd.getColumnTypeName(i + 1);
 57                 if (colTypes[i].equalsIgnoreCase("datetime")) {
 58                     f_util = true;
 59                 }
 60                 if (colTypes[i].equalsIgnoreCase("image")
 61                         || colTypes[i].equalsIgnoreCase("text")) {
 62                     f_sql = true;
 63                 }
 64                 colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
 65             }
 66             String content = parse(colnames, colTypes, colSizes);
 67  
 68             try {
 69                 FileWriter fw = new FileWriter(initcap(tablename) + ".java");
 70  
 71                 PrintWriter pw = new PrintWriter(fw);
 72                 pw.println(content);
 73                 pw.flush();
 74                 pw.close();
 75             } catch (IOException e) {
 76                 e.printStackTrace();
 77             }
 78         } catch (SQLException e) {
 79             e.printStackTrace();
 80         } finally {
 81             ConnectionFactory.getInstance().closeConnection(conn, pstmt, null);
 82             rsmd = null;
 83         }
 84     }
 85  
 86     /**
 87      *    获取当前数据中的表名称
 88      * @methodName getTablesName
 89      * @time 2015年9月29日下午4:52:26
 90      * @packageName fanshe
 91      */
 92     public List<String> getTablesName(){
 93         List<String> list = null;
 94         Connection conn = null;
 95         DatabaseMetaData md = null;
 96         ResultSet rs = null;
 97         conn = ConnectionFactory.getInstance().getConnection();
 98         try {
 99             md = conn.getMetaData();
100             rs = md.getTables(null, null, null, null);
101             if(rs!=null&&rs.next()){
102                 list = new ArrayList<String>();
103             }
104             while (rs.next()) {
105                 //System.out.println("|表"+(i++)+":"+rs.getString("TABLE_NAME"));
106                 String tableName = rs.getString("TABLE_NAME");
107                 list.add(tableName);
108             }
109  
110         } catch (SQLException e) {
111             e.printStackTrace();
112         } finally {
113             ConnectionFactory.getInstance().closeConnection(conn, null, rs);
114             md = null;
115         }
116         return list;
117     }
118  
119     /**
120      * 解析处理(生成实体类主体代码)
121      */
122     private String parse(String[] colNames, String[] colTypes, int[] colSizes) {
123         StringBuffer sb = new StringBuffer();
124         if (f_util) {
125             sb.append("import java.util.Date;
");
126         }
127         if (f_sql) {
128             sb.append("import java.sql.*;


");
129         }
130         sb.append("public class " + initcap(tablename) + " {
");
131         processAllAttrs(sb);
132         processAllMethod(sb);
133         sb.append("}
");
134  
135         //markerBean(initcap(tablename), sb.toString());
136  
137         return sb.toString();
138  
139     }
140  
141     /**
142      *  创建java 文件  将生成的属性 get/set 方法 保存到 文件中
143      * markerBean
144      * @time 2015年9月29日下午4:15:22
145      * @packageName fanshe
146      * @param className  类名称
147      * @param content    类内容  包括属性 getset 方法
148      */
149     public void markerBean(String className, String content) {
150         String folder = System.getProperty("user.dir") + "/src/fanshe/";
151  
152         File file = new File(folder);
153         if (!file.exists()) {
154             file.mkdirs();
155         }
156         String fileName = folder + className + ".java";
157  
158         try {
159             File newdao = new File(fileName);
160             FileWriter fw = new FileWriter(newdao);
161             fw.write(content);
162             fw.flush();
163             fw.close();
164         } catch (IOException e) {
165             e.printStackTrace();
166         }
167     }
168  
169     /**
170      * 生成所有的方法
171      *
172      * @param sb
173      */
174     private void processAllMethod(StringBuffer sb) {
175         for (int i = 0; i < colnames.length; i++) {
176             sb.append("	public void set" + initcap(colnames[i]) + "("
177                     + sqlType2JavaType(colTypes[i]) + " " + colnames[i]
178                     + "){
");
179             sb.append("		this." + colnames[i] + "=" + colnames[i] + ";
");
180             sb.append("	}
");
181  
182             sb.append("	public " + sqlType2JavaType(colTypes[i]) + " get"
183                     + initcap(colnames[i]) + "(){
");
184             sb.append("		return " + colnames[i] + ";
");
185             sb.append("	}
");
186         }
187     }
188  
189     /**
190      * 解析输出属性
191      *
192      * @return
193      */
194     private void processAllAttrs(StringBuffer sb) {
195         for (int i = 0; i < colnames.length; i++) {
196             sb.append("	private " + sqlType2JavaType(colTypes[i]) + " "
197                     + colnames[i] + ";
");
198  
199         }
200     }
201  
202     /**
203      * 把输入字符串的首字母改成大写
204      *
205      * @param str
206      * @return
207      */
208     private String initcap(String str) {
209         char[] ch = str.toCharArray();
210         if (ch[0] >= 'a' && ch[0] <= 'z') {
211             ch[0] = (char) (ch[0] - 32);
212         }
213         return new String(ch);
214     }
215  
216     private String sqlType2JavaType(String sqlType) {
217         if (sqlType.equalsIgnoreCase("bit")) {
218             return "bool";
219         } else if (sqlType.equalsIgnoreCase("tinyint")) {
220             return "byte";
221         } else if (sqlType.equalsIgnoreCase("smallint")) {
222             return "short";
223         } else if (sqlType.equalsIgnoreCase("int")) {
224             return "int";
225         } else if (sqlType.equalsIgnoreCase("bigint")) {
226             return "long";
227         } else if (sqlType.equalsIgnoreCase("float")) {
228             return "float";
229         } else if (sqlType.equalsIgnoreCase("decimal")
230                 || sqlType.equalsIgnoreCase("numeric")
231                 || sqlType.equalsIgnoreCase("real")) {
232             return "double";
233         } else if (sqlType.equalsIgnoreCase("money")
234                 || sqlType.equalsIgnoreCase("smallmoney")) {
235             return "double";
236         } else if (sqlType.equalsIgnoreCase("varchar")
237                 || sqlType.equalsIgnoreCase("char")
238                 || sqlType.equalsIgnoreCase("nvarchar")
239                 || sqlType.equalsIgnoreCase("nchar")) {
240             return "String";
241         } else if (sqlType.equalsIgnoreCase("datetime")) {
242             return "Date";
243         }
244  
245         else if (sqlType.equalsIgnoreCase("image")) {
246             return "Blob";
247         } else if (sqlType.equalsIgnoreCase("text")) {
248             return "Clob";
249         }
250         return null;
251     }
252  
253     public static void main(String[] args) {
254         new GenEntityTool();
255     }
256 }

获取当前数据库中 所有的表

 1     /**
 2      *    获取当前数据中的表名称
 3      * @methodName getTablesName
 4      * @time 2015年9月29日下午4:52:26
 5      * @packageName fanshe
 6      */
 7     public List<String> getTablesName(){
 8         List<String> list = null;
 9         Connection conn = null;
10         DatabaseMetaData md = null;
11         ResultSet rs = null;
12         conn = ConnectionFactory.getInstance().getConnection();
13         try {
14             md = conn.getMetaData();
15             rs = md.getTables(null, null, null, null);
16             if(rs!=null&&rs.next()){
17                 list = new ArrayList<String>();
18             }
19             while (rs.next()) {
20                 //System.out.println("|表"+(i++)+":"+rs.getString("TABLE_NAME"));
21                 String tableName = rs.getString("TABLE_NAME");
22                 list.add(tableName);
23             }
24             
25         } catch (SQLException e) {
26             e.printStackTrace();
27         } finally {
28             ConnectionFactory.getInstance().closeConnection(conn, null, rs);
29             md = null;
30         }
31         return list;
32     }
原文地址:https://www.cnblogs.com/zfy0098/p/5098986.html