MySQLToBean.java

package org.just.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern; import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.EventQueue; import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JCheckBox;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException; import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent; import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent; /**
* 此类用来将mysql的表直接生成Bean
*
* @author childlikeman@gmail.com
*/
public class MySQLToBean extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JCheckBox checkBox;
Properties p = new Properties();
String configFile = "config.ini";
private JLabel lblNewLabel_4; public MySQLToBean() { setResizable(false); setTitle("MySQL生成javabean小工具");
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); setBounds(100, 100, 484, 324); JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(null); txtLocalhost = new JTextField();
txtLocalhost.setText("localhost");
txtLocalhost.setBounds(146, 10, 147, 21);
panel.add(txtLocalhost);
txtLocalhost.setColumns(10); JLabel lblIp = new JLabel("IP:");
lblIp.setBounds(80, 13, 30, 15);
panel.add(lblIp); JLabel label = new JLabel("数据库:");
label.setBounds(80, 42, 54, 15);
panel.add(label); textField = new JTextField();
textField.setBounds(146, 39, 147, 21);
panel.add(textField);
textField.setColumns(10); JLabel label_1 = new JLabel("表名:");
label_1.setBounds(80, 127, 54, 15);
panel.add(label_1); textField_1 = new JTextField();
textField_1.setBounds(146, 124, 147, 21);
panel.add(textField_1);
textField_1.setColumns(10); JLabel label_2 = new JLabel("包名:");
label_2.setBounds(79, 156, 54, 15);
panel.add(label_2); txtComyourcom = new JTextField();
txtComyourcom.setText("com.yourcom.bean");
txtComyourcom.setBounds(146, 155, 147, 21);
panel.add(txtComyourcom);
txtComyourcom.setColumns(10); JLabel lblNewLabel = new JLabel("输出目录:");
lblNewLabel.setBounds(80, 190, 65, 15);
panel.add(lblNewLabel); textField_3 = new JTextField();
textField_3.setBounds(146, 186, 147, 21);
panel.add(textField_3);
textField_3.setColumns(10); checkBox = new JCheckBox("生成包结构目录");
checkBox.setSelected(true);
checkBox.setBounds(145, 213, 147, 23);
panel.add(checkBox); JLabel lblNewLabel_1 = new JLabel("可以指定表名,也可以不指定");
lblNewLabel_1.setBounds(303, 127, 176, 15);
panel.add(lblNewLabel_1); JLabel lblNewLabel_2 = new JLabel("* 数据库名");
lblNewLabel_2.setForeground(Color.RED);
lblNewLabel_2.setBounds(303, 42, 66, 15);
panel.add(lblNewLabel_2); JLabel lblNewLabel_3 = new JLabel("* 包结构");
lblNewLabel_3.setForeground(Color.RED);
lblNewLabel_3.setBounds(303, 158, 79, 15);
panel.add(lblNewLabel_3); JButton button = new JButton("执行");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
go();
}
});
button.setBounds(145, 242, 93, 23);
panel.add(button); textField_4 = new JTextField();
textField_4.setText("123456");
textField_4.setBounds(145, 93, 147, 21);
panel.add(textField_4);
textField_4.setColumns(10); txtRoot = new JTextField();
txtRoot.setText("root");
txtRoot.setBounds(145, 66, 148, 21);
panel.add(txtRoot);
txtRoot.setColumns(10); JLabel label_3 = new JLabel("用户名:");
label_3.setBounds(80, 69, 54, 15);
panel.add(label_3); JLabel label_4 = new JLabel("密码:");
label_4.setBounds(80, 96, 54, 15);
panel.add(label_4); lblNewLabel_4 = new JLabel("");
lblNewLabel_4.setForeground(Color.RED);
lblNewLabel_4.setBounds(248, 242, 204, 23);
panel.add(lblNewLabel_4); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {
super.windowClosing(e);
export();
System.exit(0);
} }); inport();
} static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private JTextField txtLocalhost;
private JTextField textField;
private JTextField textField_1;
private JTextField txtComyourcom;
private JTextField textField_3;
private JTextField textField_4;
private JTextField txtRoot; /**
* @param args
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) { e.printStackTrace();
} catch (InstantiationException e) { e.printStackTrace();
} catch (IllegalAccessException e) { e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) { e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MySQLToBean frame = new MySQLToBean();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} private void inport() {
File config = new File(configFile);
if (config.exists()) {
try {
InputStream is = new FileInputStream(config);
p.load(is);
is.close();
setUIVal();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
try {
config.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
} } public void setUIVal() {
txtLocalhost.setText(p.getProperty("host", "localhost"));
textField.setText(p.getProperty("database", ""));
txtRoot.setText(p.getProperty("user", "root"));
textField_4.setText(p.getProperty("pass", "123456"));
txtComyourcom.setText(p.getProperty("packname", "com.youcom.bean"));
textField_3.setText(p.getProperty("dirstr", ""));
textField_1.setText(p.getProperty("tablename", ""));
} private void export() {
String host = txtLocalhost.getText();
String database = textField.getText();
String user = txtRoot.getText();
String pass = textField_4.getText();
String packname = txtComyourcom.getText();
String dirstr = textField_3.getText();// 空表示当前目录
String tablename = textField_1.getText(); p.setProperty("host", host);
p.setProperty("database", database);
p.setProperty("user", user);
p.setProperty("pass", pass);
p.setProperty("packname", packname);
p.setProperty("dirstr", dirstr);
p.setProperty("tablename", tablename); try {
OutputStream out = new FileOutputStream(configFile);
p.store(out, "退出保存文件," + sdf.format(new Date()));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } public void setTips(String msg) {
lblNewLabel_4.setText(msg);
} public void go() {
String host = txtLocalhost.getText();
String database = textField.getText(); if (database.length() == 0) {
setTips("数据库名必填");
return;
} String user = txtRoot.getText();
String pass = textField_4.getText();
String packname = txtComyourcom.getText();
String dirstr = textField_3.getText();// 空表示当前目录
String tablename = textField_1.getText();
boolean createPackage = checkBox.getSelectedObjects() != null;
System.out.println(createPackage);
if (dirstr != null && !dirstr.isEmpty()) {
if (!dirstr.endsWith("/")) {
dirstr += "/";
}
}
File dir = new File(dirstr);
if (createPackage) {
dir = new File(dirstr + packname.replaceAll("\\.", "/"));
if (!dir.exists()) {
dir.mkdirs();
}
}
String outputdir = dir.getAbsolutePath();// bean的生成目录 Connection conn = null;
try { conn = DBManager.mysql(host, database, user, pass);
if (tablename.length() > 0) {
parseTableByShowCreate(conn, tablename, packname, outputdir);
} else {
parseAllTable(conn, packname, outputdir);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
setTips("找不到MySQL的jar包");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } /**
* 开始处理生成所有表 如果不传入表名,表示将数据库中所有表生成bean; 可以指定表名生成bean;
*/
public void parseAllTable(Connection conn, String packname, String outputdir) { String sql = "show tables";
ResultSet rs = DBManager.query(conn, sql);
try {
while (rs.next()) {
String tablename = rs.getString(1);
parseTableByShowCreate(conn, tablename, packname, outputdir);
}
DBManager.close(conn, null, rs);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} /**
* 通过 mysql的 show create table TABLE_NAME逆向生成Bean;
*
* @param conn
* @param tname
* @param outputdir
* @param packname
*/
private void parseTableByShowCreate(Connection conn, String tablename,
String packname, String outputdir) {
StringBuilder classInfo = new StringBuilder("\t/**\r\n\t*");
boolean shouldCloseConn = false; String sql = "show create table " + tablename;
ResultSet rs = null;
try {
rs = DBManager.query(conn, sql);
StringBuilder fields = new StringBuilder();
StringBuilder methods = new StringBuilder(); while (rs.next()) {
String sqlstr = rs.getString(2);
String lines[] = sqlstr.split("\r\n");
for (int i = 0; i < lines.length; i++) {
String line = lines[i];
// System.out.println(line);
// System.out.println("------------");
String regex = "\\s*`([^`]*)`\\s*(\\w+[^ ]*)\\s*(NOT\\s+NULL\\s*)?(DEFAULT\\s*([^ ]*|NULL|'0'|''|CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)\\s*)?(COMMENT\\s*'([^']*)')?\\s*,\\s*";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(line);
while (m.find()) {
String field = m.group(1);
String type = typeTrans(m.group(2));
String cmt = m.group(7);
fields.append(getFieldStr(field, type, cmt));
methods.append(getMethodStr(field, type));
// System.out.println(field);
// System.out.println(type);
// System.out.println(cmt);
}
if (i == lines.length - 1) {
classInfo.append("此类由" + getClass().getSimpleName()
+ "工具自动生成\r\n");
classInfo.append("\t*备注(数据表的comment字段):");
int index = line.indexOf("COMMENT=");
if (index != -1) {
String tmp = line.substring(index + 8);
classInfo.append(tmp.replace("'", ""));
} else {
classInfo.append("无备注信息");
}
classInfo.append("\r\n");
classInfo
.append("\t*@author childlikeman@gmail.com,http://t.qq.com/lostpig\r\n");
classInfo.append("\t*@since ");
classInfo.append(sdf.format(new Date()));
classInfo.append("\r\n\t*/\r\n\r\n");
} } }
classInfo.append("\tpublic class ")
.append(upperFirestChar(tablename)).append("{\r\n");
classInfo.append(fields);
classInfo.append(methods);
classInfo.append("\r\n");
classInfo.append("}");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally { DBManager.close(shouldCloseConn ? conn : null, null, rs);
} String packageinfo = "package " + packname + ";\r\n\r\n";
File file = new File(outputdir, upperFirestChar(tablename) + ".java");
System.out.println(file.getAbsolutePath());
try {
FileWriter fw = new FileWriter(file);
fw.write(packageinfo);
fw.write(classInfo.toString());
fw.flush();
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} /**
*
* @param type
* @return
*/
private String getMethodStr(String field, String type) {
StringBuilder get = new StringBuilder("\tpublic ");
get.append(type).append(" ");
if (type.equals("boolean")) {
get.append(field);
} else {
get.append("get");
get.append(upperFirestChar(field));
}
get.append("(){").append("\r\n\t\treturn this.").append(field)
.append(";\r\n\t}\r\n");
StringBuilder set = new StringBuilder("\tpublic void "); if (type.equals("boolean")) {
set.append(field);
} else {
set.append("set");
set.append(upperFirestChar(field));
}
set.append("(").append(type).append(" ").append(field)
.append("){\r\n\t\tthis.").append(field).append("=")
.append(field).append(";\r\n\t}\r\n");
get.append(set);
return get.toString();
} public String upperFirestChar(String src) {
return src.substring(0, 1).toUpperCase().concat(src.substring(1));
} private String getFieldStr(String field, String type, String cmt) {
StringBuilder sb = new StringBuilder();
sb.append("\t").append("private ").append(type).append(" ")
.append(field).append(";");
if (cmt != null) {
sb.append("//").append(cmt);
}
sb.append("\r\n");
return sb.toString();
} /**
* mysql的类型转换到java 类型参考文章
* http://hi.baidu.com/wwtvanessa/blog/item/9fe555945a07bd16d31b70cd.html
*/
public String typeTrans(String type) {
if (type.contains("tinyint")) {
return "boolean";
} else if (type.contains("int")) {
return "int";
} else if (type.contains("varchar") || type.contains("date")
|| type.contains("time") || type.contains("datetime")
|| type.contains("timestamp") || type.contains("text")
|| type.contains("enum") || type.contains("set")) {
return "String";
} else if (type.contains("binary") || type.contains("blob")) {
return "byte[]";
} else {
return "String";
}
}
}

DBManager.java

package org.just.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; //本类专门用来连接数据库,可以作为固定的工具类使用(记下来即可)
public class DBManager {
// 定义一个静态的连接对象用来连接数据库
// private static Connection conn = null;
// 定一个静态的语句对象,用来执行sql语句
// private static Statement stmt = null;
// 定义一个静态的结果集对象用来存放执行sql语句后查询得到的结果
// private static ResultSet rs = null; /**
* 连接数据库的方法
*
* @return conn 返回一个连接对象
*/
public static Connection mssql(String url, String user, String pass) {
Connection conn = null;
try {
// 1、加载连接驱动
// "jdbc:odbc:bookdemo"
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// 2、连接到数据库(获得连接对象)
// 通过连接管理器(DriverManager)类的一个方法来获得连接对象,里面的参数表示我们连接到数据源bookdemo
conn = DriverManager.getConnection(url, user, pass);
} catch (ClassNotFoundException e) {
// 以堆栈的方式将错误信息打印出来
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return conn; // 将连接对象返回
} /**
* 连接数据库的方法
*
* @return conn 返回一个连接对象
* @throws ClassNotFoundException
* @throws SQLException
*/
public static Connection mysql(String url, String user, String pass)
throws ClassNotFoundException, SQLException {
Connection conn = null; // 1、加载连接驱动
// "jdbc:odbc:bookdemo"
Class.forName("com.mysql.jdbc.Driver");
// 2、连接到数据库(获得连接对象)
// 通过连接管理器(DriverManager)类的一个方法来获得连接对象,里面的参数表示我们连接到数据源bookdemo
conn = DriverManager.getConnection(url, user, pass); return conn; // 将连接对象返回
} /**
* 动漫网的mysql数据库连接
* @throws SQLException
* @throws ClassNotFoundException
*/
public static Connection mysql(String host, String database, String user,
String pass) throws ClassNotFoundException, SQLException {
String url = "jdbc:mysql://" + host + "/" + database
+ "?useUnicode=true&amp;characterEncoding=UTF-8";
return mysql(url, user, pass);
} /**
* 本函数用来执行用户传入的sql语句(仅限于select语句)
*
* @param sql
* 传入的sql语句,等待执行
* @return 返回执行sql语句后的结果集对象
*/
public static ResultSet query(Connection conn, String sql) {
ResultSet rs = null;
try {
// 3、通过连接对象创建一个语句对象stmt,用来执行sql语句
Statement stmt = conn.createStatement();
// 4、执行sql语句,得到一个rs(结果集对象)
rs = stmt.executeQuery(sql);
} catch (Exception e) { // 错误处理,暂时不用理会
e.printStackTrace();
}
return rs; // 将查询得到的结果集对象返回
} /**
* 本方法用来执行更新语句,并返回影响了多少行(insert,update,delete)
*
* @param sql
* 传入的sql语句,等待执行
* @return 返回执行sql语句后的结果集对象
*/
public static int update(Connection conn, String sql) {
// 执行sql语句前先连接到数据库
Statement stmt = null;
int i = 0;
try {
// 通过连接对象创建一个语句对象stmt,用来执行sql语句
stmt = conn.createStatement();
// 执行更新语句,并返回影响了多少行
i = stmt.executeUpdate(sql);
} catch (Exception e) { // 错误处理,暂时不用理会
e.printStackTrace();
} finally {
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return i;
} public static void close(Connection conn, Statement stmt, ResultSet rs) { try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

mysql表生成JavaBean的更多相关文章

  1. java工具类–自动将数据库表生成javabean

    最近和数据库的表打交道挺多的,因为暂时做的是接口活. 在这过程中发现要把表转换成对应的javabean类型,字段少的表还行,如果不小心碰到几十个字段的他妈的写起来就有点麻烦了,万一碰到几百个的呢,那不 ...

  2. Oracle表生成JavaBean

    package com.batch.tabletojava import java.io.DataOutputStream; import java.io.File; import java.io.F ...

  3. MYSQL 表转 JavaBean 工具类

    import org.apache.commons.lang.StringUtils; import java.io.BufferedWriter; import java.io.File; impo ...

  4. 在django中如何通过已有的mysql表生成django的model

    第一步:先是在项目中建立一个app:python manage.py startapp app01 第二步:python manage.py inspectdb > app01/models.p ...

  5. 根据表结构自动生成JavaBean,史上最强最专业的表结构转JavaBean的工具(第2版)

             目录:                 第1版:http://blog.csdn.net/vipbooks/article/details/51912143              ...

  6. 【工具篇】利用DBExportDoc V1.0 For MySQL自动生成数据库表结构文档

    对于DBA或开发来说,如何规范化你的数据库表结构文档是灰常之重要的一件事情.但是当你的库,你的表排山倒海滴多的时候,你就会很头疼了. 推荐一款工具DBExportDoc V1.0 For MySQL( ...

  7. MySQL 如何生成月份表

    MySQL 如何生成月份表 如果遇到按照月份统计信息的时候,常用的统计方式就是用month表去连接order表,下面就是生成月份表的过程 1.首先是建表 CREATE TABLE `sn_month` ...

  8. MySQL 如何生成日期表

    MySQL 如何生成日期表 在开发过程中,经常会遇到统计问题,通常交易信息都不是连续的,此时,统计出来的数据都是不连续的,所以提前生成一个时期表,当没有交易数据的时候填充0,就可以了,下面是生成日期表 ...

  9. 使用PowerDesigner创建物理模型并生成SQL语句在MySQL中生成表

    我使用的PowerDesigner的版本为16.5,创建物理模型后,使用PowerDesigner生成的SQL语句,在MySQL中创建表. 1. 打开Power Designer软件,在弹出的欢迎对话 ...

随机推荐

  1. javaScript-什么是变量?

    什么是变量? 从字面上看,变量是可变的量:从编程角度讲,变量是用于存储某种/某些数值的存储器.我们可以把变量看做一个盒子,为了区分盒子,可以用BOX1,BOX2等名称代表不同盒子,BOX1就是盒子的名 ...

  2. POJ 3685 二分套二分

    Matrix Given a N × N matrix A, whose element in the i-th row and j-th column Aij is an number that e ...

  3. Configure Always On Availability Group for SQL Server on RHEL——Red Hat Enterprise Linux上配置SQL Server Always On Availability Group

    下面简单介绍一下如何在Red Hat Enterprise Linux上一步一步创建一个SQL Server AG(Always On Availability Group),以及配置过程中遇到的坑的 ...

  4. ssh框架整合之登录以及增删改查

    1.首先阐述一下我用得开发工具,myeclipse2017+oracle,所以我的基本配置步骤可能不一样,下面我用几张图来详解我的开发步骤. ---1先配置structs (Target 选择apac ...

  5. 基于查表的整数霍夫变换方法实现(matlab)

    暂时先用matlab把算法弄一下,这是基于查表的整数霍夫变换方法实现及解释. 接着再实现FPGA的霍夫变换. 霍夫变换原理和算法这里不多说,可参考以下链接: http://blog.csdn.net/ ...

  6. Java入门以及Java中的常量与变量总结

    JDK与JRE的区别: JDK给开发人员使用(包含开发工具),JRE给客户使用(运行java程序的核心类库),JDK包含JRE关键字的含义: JAVA语言赋予特殊含义,具有专门用途的单词,关键字的单词 ...

  7. js判断是否是ie浏览器且给出ie版本

    之前懒得写判断ie版本js,因为网上关于这方面的代码太多了,所以从网上拷贝了一个,放到项目上才发现由于时效性的问题,代码不生效.就自己写一个吧. 怎么去看浏览器的内核等信息 ---- js的全局对象w ...

  8. Realm的简单使用

    Realm个人理解: 它主要是一套移动端数据库框架,将对数据库表的操作转换为对对象的操作,如果是学过Java ORM框架的同学使用Realm起来应该上手比较快一点.而且据我所知Realm不仅支持Obj ...

  9. C#基础知识-XML介绍及基本操作(十)

    在讲了一系列的基础文档之后,现在开始讲一些实例.对于一些数据不是很大的程序,或者只是一些配置文件,需要本地存储的,完全可以使用XML代替数据库,因为只是去操作单个文件会比操作数据库要简单很多,在程序中 ...

  10. 360安全检测出的WordPress漏洞的修复方法

    1.跨站脚本攻击(XSS) 这个漏洞注意是因为用户评论可以提交代码,有安全风险.虽然你的WordPress以及是最新版,但是你的WordPress主题却不一定跟着更新!因此,需要稍微修改一下评论相关的 ...