MySQL automatically generates JavaBean

Source: Internet
Author: User
Tags gettext save file stmt

Directly on the code:


Database Link Tool Class:

Import Java.sql.connection;import java.sql.drivermanager;import java.sql.resultset;import java.sql.SQLException; Import java.sql.statement;//This class is specifically used to connect to a database and can be used as a fixed tool class (note) public class DBManager {//define a static connection object to connect to the database//private static Connection conn = null;//A static statement object used to execute the SQL statement//private static Statement stmt = null;//define a static result set object to hold the query after executing the SQL statement Results obtained//private static ResultSet rs = null;/** * method to connect to the database * * @return Conn Returns a Connection object */public static Connection MSSQL (Stri Ng URL, string user, String pass) {Connection conn = null;try {///1, Load Connection driver//"Jdbc:odbc:bookdemo" Class.forName ("SUN.JDBC.O Dbc. Jdbcodbcdriver ");//2, connect to the database (Get Connection object)//The connection object is obtained through a method of the Connection Manager (DriverManager) class, which indicates that we connect to the data source Bookdemoconn = Drivermanager.getconnection (URL, user, pass);} catch (ClassNotFoundException e) {//The error message is printed out as a stack e.printstacktrace ();} catch (SQLException e) {//TODO auto-generated Catch Blocke.printstacktrace ();} Return conn; Return Connection Object}/** * method to connect to database * * @return conn Return a Connection object * @throws classnotfoundexception * @throws SQLException */public static Connection mysql (string url, string user, String pass) throws Classnotfoundexceptio N, SQLException {Connection conn = null;//1, load Connection driver//"Jdbc:odbc:bookdemo" Class.forName ("Com.mysql.jdbc.Driver");//2, Connect to a database (get a Connection object)//The connection object is obtained through a method of the Connection Manager (DriverManager) class, which indicates that we connect to the data source Bookdemoconn = Drivermanager.getconnection ( URL, user, pass); return conn; Return the Connection object to}/** * The MySQL database connection of the anime Web * @throws SQLException * @throws classnotfoundexception */public static Connection MySQL (string host, String database, String User,string Pass) throws ClassNotFoundException, SQLException {string url = "Jdbc:my sql://"+ host +"/"+ database+"? Useunicode=true&characterencoding=utf-8 "; return MySQL (URL, user, pass);}  /** * This function is used to execute user-passed SQL statements (SELECT statements only) * * @param SQL * Incoming SQL statement, wait for execution * @return return result set object after executing SQL statement */public static ResultSet query (Connection conn, String sql) {ResultSet rs = null;try {///3), create a statement object from the Connection object stmt, to execute the SQL statement statement stmt = Conn.createstatement();//4, Execute SQL statement, get an RS (Result set object) rs = stmt.executequery (sql);} catch (Exception e) {//error handling, ignore E.printstacktrace ();} Return RS; Returns the result set object of the query}/** * This method is used to execute an UPDATE statement and returns how many rows are affected (insert,update,delete) * * @param SQL * Incoming SQL statement, waiting for execution * @return return The result set object after executing the SQL statement */public static int update (Connection conn, String sql) {//Execute SQL statement before connecting to database statement stmt = Null;int i = 0; try {//Creates a statement object stmt through the Connection object, which executes the SQL statement stmt = conn.createstatement ();//Executes the UPDATE statement and returns the number of rows affected by i = stmt.executeupdate (sql);} catch (Exception e) {//error handling, ignore E.printstacktrace ();} finally {try {stmt.close ()} catch (SQLException e) {//TODO Aut O-generated catch Blocke.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 Blocke.printstacktrace ();}}}

Javebean Generate class:

Import Java.awt.borderlayout;import java.awt.color;import java.awt.eventqueue;import java.awt.event.ActionEvent; Import Java.awt.event.actionlistener;import Java.awt.event.windowadapter;import Java.awt.event.windowevent;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 Javax.swing.jbutton;import Javax.swing.jcheckbox;import Javax.swing.jframe;import Javax.swing.jlabel;import Javax.swing.jpanel;import Javax.swing.JTextField;import Javax.swing.uimanager;import javax.swing.unsupportedlookandfeelexception;/** * This class is used to generate the MySQL table directly from the bean * * @author Ming * /public class Mysqltobean extends JFrame {/** * */private static final long Serialversionuid = 1L;private Jcheckbox CheckBox; Properties P = new properties (); String configfile = "Config.ini";p rivate JLabel lblnewlabel_4;public Mysqltobean () {setresizable (false); Settitle (" MySQL generate JavaBean gadget "); Setdefaultcloseoperation (jframe.do_nothing_on_close); setbounds (100, 100, 484, 324); JPanel panel = new JPanel (); Getcontentpane (). Add (Panel, borderlayout.center);p anel.setlayout (null); txtlocalhost = new JTextField (); Txtlocalhost.settext ("localhost"), txtlocalhost.setbounds (146, 147, +);p Anel.add (txtlocalhost); Txtlocalhost.setcolumns (10); JLabel lblip = new JLabel ("IP:"); Lblip.setbounds (+,--);p Anel.add (Lblip); JLabel label = new JLabel ("Database:"); Label.setbounds (n, A, si, si);p anel.add (label); TextField = new JTextField (); Textfield.setbounds (146, 10, 147, TextField);p Anel.add (textfield.setcolumns); JLabel label_1 = new JLabel ("Table name:"), Label_1.setbounds (127, Wu, Wu);p anel.add (label_1); textfield_1 = new JTextField (); Textfield_1.setbounds (146, 124, 147,);p Anel.add (textfield_1); tExtfield_1.setcolumns (10); JLabel label_2 = new JLabel ("Package Name:"), Label_2.setbounds (156, Wu, Wu);p anel.add (label_2); txtcomyourcom = new JTextField ( ); Txtcomyourcom.settext ("Com.yourcom.bean"); Txtcomyourcom.setbounds (146, 155, 147,);p Anel.add (txtcomyourcom); Txtcomyourcom.setcolumns (10); JLabel Lblnewlabel = new JLabel ("Output directory:"), Lblnewlabel.setbounds (n, O, N, a);p Anel.add (lblnewlabel); textfield_3 = New JTextField (); Textfield_3.setbounds (146, 186, 147,);p Anel.add (textfield_3); Textfield_3.setcolumns (10); CheckBox = new Jcheckbox ("Generate Package Structure directory"); checkbox.setselected (true); Checkbox.setbounds (145, 213, 147, 23°c);p Anel.add ( CheckBox); JLabel lblnewlabel_1 = new JLabel ("You can specify a table name, or you can specify no") lblnewlabel_1.setbounds (303, 127, 176,;p) Anel.add (lblnewlabel_1 ); JLabel lblnewlabel_2 = new JLabel ("* Database name"); Lblnewlabel_2.setforeground (color.red); Lblnewlabel_2.setbounds (303, 42, ;p Anel.add (lblnewlabel_2); JLabel lblnewlabel_3 = new JLabel ("* Package structure"); Lblnewlabel_3.setforeground (color.red); lblnewlabel_3.setBounds (303, 158, Anel.add (lblnewlabel_3);p; JButton button = new JButton ("Execute"), Button.addactionlistener (new ActionListener () {public void actionperformed ( ActionEvent e) {go ();}}); Button.setbounds (145, 242, 123456);p anel.add (button), Textfield_4 = new JTextField (); Textfield_4.setbounds (145, 147, Textfield_4);p Anel.add (textfield_4.setcolumns); Txtroot (JTextField) = new () ; Txtroot.settext ("root"); Txtroot.setbounds (145, 148, 10);p Anel.add (txtroot); JLabel label_3 = new JLabel ("User name:"), Label_3.setbounds (N, A, Wu, Wu);p anel.add (label_3); JLabel label_4 = new JLabel ("Password:"), Label_4.setbounds (n, A, si, si);p anel.add (label_4); lblnewlabel_4 = new JLabel (""); Lblnewlabel_4.setforeground (color.red), Lblnewlabel_4.setbounds (248, 242, 204, 23°c);p Anel.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");p rivate jtextfield txtlocalhost;private JTextField textfield;private JTextField textfield_1;private JTextField txtcomyourcom;private jtextfield textfield_3;private JTextField textField_4 ;p rivate JTextField txtroot;/** * @param args */public static void main (string[] args) {try {Uimanager.setlookandfeel (UIMa Nager.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 Blocke.printstacktrace ();} catch (IOException e) {//TODO Auto-generated catch Blocke.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 ("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 ();//null indicates the current directory 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, "Exit Save file," + Sdf.format (new Date ()));} catch (FileNotFoundException e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//Todo Au To-generated catch Blocke.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 ("database name required"); return;} String user = Txtroot.gettext (); String pass = Textfield_4.gettext (); String packname = Txtcomyourcom.gettext (); String dirstr = Textfield_3.gettext ();//null indicates the current directory 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 generation directory Connection conn = null;try {conn = Dbmanager.mysql (host, database, US Er, pass); if (Tablename.length () > 0) {parsetablebyshowcreate (conn, TableName, Packname, OutputDir);} else { Parsealltable (conn, packname, OutputDir);}} catch (ClassNotFoundException e) {//TODO auto-generated catch Blocke.printstacktrace (); Settips ("Unable to find MySQL jar package");} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} /** * Start processing generate all tables if you do not pass in the table name, the bean is generated for all tables in the database; You can specify a table name to generate a 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 Blocke.printstacktrace ();}} /** * Reverse-generate beans through the MySQL show create TABLE table_name; * * @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 = "desc" + tablename; ResultSet rs = null;try {rs = dbmanager.query (conn, SQL); StringBuilder fields = new StringBuilder (); StringBuilder methods = new StringBuilder (); int i = 0;while (Rs.next ()) {String fieldName = rs.getstring ("Field"); System.out.println (rs.getstring ("Type")); String FieldType = "", if (rs.getstring ("type"). Contains ("(")) {FieldType = Typetrans (rs.getstring ("type"). SUBSTRING (0 , Rs.getstring ("Type"). IndexOf ("("))); else {FieldType = Typetrans (rs.getstring ("Type"));} Fields.Append (Getfieldstr (fieldName, FieldType, null)); Methods.append (GetMethodStr (FieldName, FieldType)); if (i = = 0) {classinfo.append ("This class is generated by" + getclass (). Getsimplename () + "tools automatically generate \ r \ n"); Classinfo.append ("\ r \ n"), Classinfo.append ("\t* @author \ r \ n"), Classinfo.append ("\t* @since"); Classinfo.append ( Sdf.format (New Date ())); Classinfo.append ("\r\n\t*/\r\n\r\n");} i++;} 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 Blocke.printstacktrace ();} finally {Dbmanager.close ( Shouldcloseconn? Conn:null, NULL, RS);} String PackageInfo = "package" + packname.replace ("src.", "") + "; \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 Blocke.printstacktrace ();}} /** * * @param type * @return */private string getmethodstr (String field, String type) {StringBuilder get = new Stringbui Lder ("\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 type conversion to Java type reference article * */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.contain S ("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";}}}



MySQL automatically generates JavaBean

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.