需求
现有数据库有几百张表,需要将表对应的JavaBean写完。由于表数量太多,一个一个写太浪费时间,所以写了个批量导入的程序。
解决思路
1、mysql
使用show TABLES;获取所有的表名
使用desc 表名;获取相应表的结构
2、生成javabean规则
(1)表名 到 类名:首字母大写,”_”去掉且后面的字母大写
例如:表ecs_account_log对应为EcsAccountLog
(2)列类型 到 Bean属性类型
列包含”int”对应为”Integer”
列包含”char”、”text”对应为”String”
列包含”time”、”date”对应为”Date”
列包含”float”、”decimal”对应为”Double”
列其他的对应为”Unknow” 方便找到漏掉的列类型
代码
package common.database;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MysqlToBeans {
static String driver = "com.mysql.jdbc.Driver";
static String url = "jdbc:mysql://localhost:3306/gyxshop?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true";
static String user = "root";
static String password = "111111";
static StringBuffer sb = new StringBuffer();
private static Statement stmt = null;
private static Connection conn = null;
private static OutputStreamWriter osw = null;
private static BufferedWriter bw = null;
private static FileOutputStream fos = null;
private static void writeData(String message, String className) {
String file = "D:\\javabeans\\" + className + ".java";
try {
fos = new FileOutputStream(file);
osw = new OutputStreamWriter(fos);
bw = new BufferedWriter(osw);
bw.write(message);
bw.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 根据表名查到字段 名称类型
public static void getTableDetatils(String tablename, String jbname) {
ResultSet rs = null;
try {
conn = DriverManager.getConnection(url, user, password);
// 执行sql语句
stmt = conn.createStatement();
rs = stmt.