Application First Run database Configuration applet (Java Edition)

Source: Internet
Author: User
Tags generator gettext

Application Initialization Database Configuration applet

Previously wrote a Java version of the information management system, but the deployment of the system also need to manually configure the database and import some initialized data to let the system run, so I was wondering if you can write a small program to automatically deploy the database and import some initialization data when the system is first run. Then we have the following ideas:

At the entrance of the application to determine whether the database has been configured to complete, if the configuration is completed into the normal login system to complete normal operation can, if not configured to enter the database configuration of the small program to complete the database configuration and then enter the system, but how to determine whether it has been configured to complete, here I use the comparison of the original method, When configuring the database, the system automatically generates a database-related configuration file in the relevant directory, which describes the type of database, the user name of the database, the password of the database (which is addressed after the security issue), and the database name that the application uses for the database that is about to be automatically created. Therefore, when the application starts, the system will detect the relevant path under the configuration file, if the file exists, the database configuration is complete, otherwise the system is the first run, you need to start the database configuration applet. After entering the database configuration applet, a pop-up dialog will pop up, we need to select the database to use and enter the database user name, password and the name of the database used by the system, click the Test button to see if you can connect to the database, if you can complete the connection will be a more initialization button, Clicking the Initialize button executes the corresponding operations such as creating a database data table and importing data, which can be done by reading the initialization file (which is the SQL statement that was initialized in the file), completing the initialization of the entire database, and then invoking the normal login program to log into the system.

So the entire process is summed up by running the application--to determine if there is a database configuration file (config. metabase) in the relevant directory (with the normal login program)--and if not, run the database initialization applet--Select the database type, Enter the user name password and the name of the newly created database-click the Test button (the test does not retry by checking the database)-click the Initialize button to complete the initialization when the initialization task is complete and jump to the normal login program.

Procedure entry Judgment procedure

 PackageHxy;ImportJava.io.File;classCreatedbconfig { PublicCreatedbconfig () {Try{File File=NewFile ("config"); File FilePath=NewFile ("Config//config.xml"); if(!file.exists ()) {                if(File.mkdir ()) {if(!filepath.exists ()) {                        NewDbform (); }Else{System.out.print ("Configuration file creation failed!!!" "); }                                            }                Else{System.out.println ("Directory Creation failed!!!" "); }            }            Else{                if(!filepath.exists ()) {                    NewDbform (); }Else{System.out.println ("The database has been configured successfully directly into the application!!! "); }            }                    } Catch(Exception e) {e.printstacktrace (); }                        }}

Database selection interface and Control monitor program (complete the collection of configuration data and then hand it to the configuration file generator to generate the appropriate profile)

 PackageHxy;Importjava.awt.BorderLayout;ImportJava.awt.Font;Importjava.awt.event.ActionEvent;ImportJava.awt.event.ActionListener;Importjava.sql.SQLException;ImportJavax.swing.DefaultComboBoxModel;ImportJavax.swing.JButton;ImportJavax.swing.JComboBox;ImportJavax.swing.JDialog;ImportJavax.swing.JLabel;ImportJavax.swing.JOptionPane;ImportJavax.swing.JPanel;ImportJavax.swing.JPasswordField;ImportJavax.swing.JTextField;Importjavax.swing.SwingConstants;ImportJavax.swing.border.EmptyBorder;classDbformextendsJDialog {Private Static Final LongSerialversionuid = 1L; Private FinalJPanel Contentpanel =NewJPanel (); PrivateJTextField UserName; PrivateJPasswordField password; PrivateJTextField DatabaseName; PrivateJcombobox<string>DatabaseType; PrivateJButton OKButton; PrivateDatabase dbdatabase; @SuppressWarnings ({"Unchecked", "Rawtypes" })     PublicDbform () {Settitle ("Database"); SetVisible (true);        Setdefaultcloseoperation (Jdialog.dispose_on_close); SetBounds (100, 100, 357, 276); Getcontentpane (). setlayout (NewBorderLayout ()); Contentpanel.setborder (NewEmptyborder (5, 5, 5, 5));        Getcontentpane (). Add (Contentpanel, borderlayout.center); Contentpanel.setlayout (NULL); JLabel Lblnewlabel=NewJLabel ("Databaseset"); Lblnewlabel.setfont (NewFont ("Arial", Font.plain, 14));        Lblnewlabel.sethorizontalalignment (Swingconstants.center); Lblnewlabel.setbounds (114, 10, 108, 15);                Contentpanel.add (Lblnewlabel); JLabel Lbldatabasetype=NewJLabel ("DatabaseType");        Lbldatabasetype.sethorizontalalignment (Swingconstants.center); Lbldatabasetype.setbounds (64, 42, 82, 15);                Contentpanel.add (Lbldatabasetype); DatabaseType=NewJComboBox (); Databasetype.setmodel (NewDefaultComboBoxModel (NewString[] {"MYSQL", "SQL Server"})); Databasetype.setbounds (181, 39, 108, 21);                Contentpanel.add (DatabaseType); JLabel Lblusername=NewJLabel ("UserName");        Lblusername.sethorizontalalignment (Swingconstants.center); Lblusername.setbounds (64, 76, 82, 15);                Contentpanel.add (Lblusername); UserName=NewJTextField (); Username.setbounds (181, 73, 108, 21);        Contentpanel.add (UserName); Username.setcolumns (10); JLabel Lblpassword=NewJLabel ("Password");        Lblpassword.sethorizontalalignment (Swingconstants.center); Lblpassword.setbounds (64, 113, 82, 15);                Contentpanel.add (Lblpassword); Password=NewJPasswordField (); Password.setbounds (181, 110, 108, 21);                Contentpanel.add (password); OKButton=NewJButton ("OK"); Okbutton.setvisible (false); //okbutton.setvisible (TRUE); //OKButton Listener SetOkbutton.addactionlistener (NewActionListener () { Public voidactionperformed (ActionEvent arg0) {//Database db = Getdatabase (); //Initial default database settings complete, next create new database and create TABLE initialization//Create a Connection objectString DBName =Dbdatabase.getname (); Dbdatabase.setname ("MySQL"); Connectdatabase Conn=Newconnectdatabase (dbdatabase); //gets the connected Statement object                Try {                    ///Create a new database and change the default database to a new databaseConn.getstate (). executeupdate ("CREATE DATABASE" +dbname+ ";");                    Conn.getstate (). Close ();                    Conn.getconn (). Close ();                    Dbdatabase.setname (DBName); XMLReader XR=NewXMLReader ();                    Xr.setxml (dbdatabase); Joptionpane.showmessagedialog (OKButton,"Database initialization successful!!!" "); Dispose ();//new LogIn ();SYSTEM.OUT.PRINTLN ("Database configuration successfully entered the application System!!! "); } Catch(SQLException e) {joptionpane.showmessagedialog (OKButton,"Database initialization failed!!!" "+e);                E.printstacktrace ();        }            }        }); Okbutton.setbounds (71, 191, 93, 23);                Contentpanel.add (OKButton); JButton Testbutton=NewJButton ("Test"); /////////////testbutton ListenerTestbutton.addactionlistener (NewActionListener () { Public voidactionperformed (ActionEvent e) {dbdatabase=getdatabase (); String DbName=Dbdatabase.getname (); Dbdatabase.setname ("MySQL"); Connectdatabase Conn=Newconnectdatabase (dbdatabase); if(Conn.getconn ()! =NULL) {okbutton.setvisible (true); Joptionpane.showmessagedialog (Testbutton,"Test successed!!!");                Dbdatabase.setname (DbName); }                Else{joptionpane.showmessagedialog (Testbutton,"Test Failed!!!");        }                            }        }); Testbutton.setbounds (191, 191, 93, 23);                Contentpanel.add (Testbutton); JLabel Lblnewlabel_1=NewJLabel ("Database");        Lblnewlabel_1.sethorizontalalignment (Swingconstants.center); Lblnewlabel_1.setbounds (64, 155, 82, 15);                Contentpanel.add (Lblnewlabel_1); DatabaseName=NewJTextField (); Databasename.setbounds (181, 152, 108, 21);        Contentpanel.add (DatabaseName); Databasename.setcolumns (10); } @SuppressWarnings ("Static-access")     PublicDatabase Getdatabase () {Database db=NewDatabase (); String DbType=Databasetype.getselecteditem (). toString (). Trim ();        System.out.println (DbType); String DbUser=username.gettext (). Trim (); @SuppressWarnings ("Deprecation") String Dbpassword=password.gettext (). Trim (); String DbName=databasename.gettext (). Trim (); if(dbtype==NULL|dbuser==NULL|dbpassword==NULL|dbname==NULL){            NewJoptionpane (). Showmessagedialog (OKButton, "please complete database information!!!");; }        Else{            if(Dbtype.equals ("MYSQL") {db.settype (dbType); Db.setdriver ("Com.mysql.jdbc.Driver"); Db.seturi ("LocalHost"); Db.setport ("3306");                Db.setuser (DbUser);                Db.setpassword (Dbpassword);            Db.setname (DbName); }            Else{db.settype (dbType); Db.setdriver ("Com.microsoft.sqlserver.jdbc.SQLServerDriver"); Db.seturi ("LocalHost"); Db.setport ("1433");                Db.setuser (DbUser);                Db.setpassword (Dbpassword);            Db.setname (DbName); }        }                    returnDB; }    }

The configuration file generator is to write the information about the database to the configuration file for the system to connect to the database when read, so there is a good benefit of generating the configuration file here is that my program does not need to write dead is in the program need to completely write the information about the database to enter, Here I just need to read the configuration file and inject it into the relevant method. As for the configuration file generator is to create a file, and then according to the corresponding configuration data written to the file, of course, this is an XML file, you can use dom4j and so on to scientific writing and modification, but this is relatively simple and rude, as for the XML file Parser and generator program in the future blog post corresponding to.

This small program is entirely because of their own small ideas and small guess to practice writing and applied to my previous information management system, the above is a small program all the code part, the program complete code in my GitHub (https://github.com/ Huangxinyuan650/connectdatabase) Welcome everyone to criticize

Application First Run database Configuration applet (Java Edition)

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.