應用程式初次運行資料庫配置小程式(Java版)

來源:互聯網
上載者:User

標籤:入口   .exe   oca   listener   awt   sql語句   批評   bpa   access   

 應用程式初始化資料庫配置小程式

  之前寫過一個Java版的資訊管理系統,但部署系統的時候還需要手動的去設定資料庫和匯入一些初始化的資料才能讓系統運行起來,所以我在想是不是可以寫一個小程式在系統初次啟動並執行時候自動部署資料庫和匯入一些初始化資料。然後就有了以下的思路:

  在應用程式入口處判斷資料庫是否已經配置完成,若配置完成則進入正常的登入系統完成正常操作即可,若未配置則進入資料庫配置的小程式完成資料庫配置然後再進入系統,但如何來判斷是否已經配置完成呢,在這裡我用的是比較原始的方法,設定資料庫的時候系統會在相關目錄下自動產生一個關於資料庫相關的設定檔(config.xml),該設定檔說明了資料庫的種類,資料庫的使用者名稱,資料庫的密碼(涉及到的安全性問題之後再處理),以及應用程式所用到資料庫也就是即將自動建立的資料庫名,所以在應用程式啟動的時候系統會去檢測相關路徑下是否有該設定檔,若該檔案存在則資料庫配置完成,否則該系統是初次運行,需要啟動資料庫配置小程式。進入資料庫配置小程式後,會彈出一個彈出式對話方塊,我們需要選擇使用到的資料庫以及輸入資料庫使用者名稱,密碼以及系統用到的資料庫的名,點擊測試按鈕查看是否可以串連上資料庫,若能完成串連則會多出一個初始化按鈕,點擊初始化按鈕會執行相應的建立資料庫資料表以及匯入資料等操作,而這些操作則可以通過讀取初始設定檔案(檔案中是初始化執行的sql語句),初始化完成即完成了整個資料庫的初始化任務,然後會調用正常的登入程式登入進入系統。

  所以整個流程總結下來就是,運行應用程式——>判斷相關目錄下是否有資料庫的設定檔(config.xml)(有則進入正常的登入程式)——>若沒有則運行資料庫初始化小程式——>選擇資料庫類型,輸入使用者名稱密碼以及建立的資料庫的名——>點擊測試按鈕(測試不通過檢查資料庫重試)——>測試成功則點擊初始化按鈕完成初始化——>初始化任務完成後會跳轉到正常的登入程式。

  程式入口判斷程式

package hxy;import java.io.File;class CreateDBConfig {    public CreateDBConfig(){        try {            File file = new File("config");            File filePath = new File("config//config.xml");            if(!file.exists()){                if(file.mkdir()){                    if(!filePath.exists()){                        new DBForm();                    }else{                        System.out.print("設定檔建立失敗!!!");                    }                                            }                else{                    System.out.println("目錄建立失敗!!!");                }            }            else{                if(!filePath.exists()){                    new DBForm();                }else{                    System.out.println("資料庫已經配置成功直接進入應用!!!");                }            }                    } catch (Exception e) {            e.printStackTrace();        }                        }}

資料庫選擇介面以及控制項監視器程式(完成配置資料的收集然後交給設定檔產生程式產生相應的設定檔)

package hxy;import java.awt.BorderLayout;import java.awt.Font;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.sql.SQLException;import javax.swing.DefaultComboBoxModel;import javax.swing.JButton;import javax.swing.JComboBox;import javax.swing.JDialog;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JPasswordField;import javax.swing.JTextField;import javax.swing.SwingConstants;import javax.swing.border.EmptyBorder;class DBForm extends JDialog {    private static final long serialVersionUID = 1L;    private final JPanel contentPanel = new JPanel();    private JTextField userName;    private JPasswordField password;    private JTextField databaseName;    private JComboBox<String> databaseType;    private JButton okButton;    private Database DBdatabase;        @SuppressWarnings({ "unchecked", "rawtypes" })    public DBForm() {        setTitle("Database");        setVisible(true);        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);        setBounds(100, 100, 357, 276);        getContentPane().setLayout(new BorderLayout());        contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));        getContentPane().add(contentPanel, BorderLayout.CENTER);        contentPanel.setLayout(null);                JLabel lblNewLabel = new JLabel("DatabaseSet");        lblNewLabel.setFont(new Font("宋體", Font.PLAIN, 14));        lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);        lblNewLabel.setBounds(114, 10, 108, 15);        contentPanel.add(lblNewLabel);                JLabel lblDatabasetype = new JLabel("DatabaseType");        lblDatabasetype.setHorizontalAlignment(SwingConstants.CENTER);        lblDatabasetype.setBounds(64, 42, 82, 15);        contentPanel.add(lblDatabasetype);                databaseType = new JComboBox();        databaseType.setModel(new DefaultComboBoxModel(new String[] {"MySql", "SQLServer"}));        databaseType.setBounds(181, 39, 108, 21);        contentPanel.add(databaseType);                JLabel lblUsername = new JLabel("UserName");        lblUsername.setHorizontalAlignment(SwingConstants.CENTER);        lblUsername.setBounds(64, 76, 82, 15);        contentPanel.add(lblUsername);                userName = new JTextField();        userName.setBounds(181, 73, 108, 21);        contentPanel.add(userName);        userName.setColumns(10);                JLabel lblPassword = new JLabel("Password");        lblPassword.setHorizontalAlignment(SwingConstants.CENTER);        lblPassword.setBounds(64, 113, 82, 15);        contentPanel.add(lblPassword);                password = new JPasswordField();        password.setBounds(181, 110, 108, 21);        contentPanel.add(password);                okButton = new JButton("OK");        okButton.setVisible(false);        //okButton.setVisible(true);        //OKButton listener set        okButton.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent arg0) {//                Database db = getDatabase();                                //初始預設資料庫設定完成,接下來建立新的資料庫並建立表初始化                //建立連線物件                String dBName = DBdatabase.getName();                DBdatabase.setName("mysql");                ConnectDatabase conn = new ConnectDatabase(DBdatabase);                //擷取串連的statement對象                try {                    ///建立新的資料庫並對並將預設資料庫改為建立的資料庫                    conn.getState().executeUpdate("create database "+dBName+";");                    conn.getState().close();                    conn.getConn().close();                    DBdatabase.setName(dBName);                    XMLReader xr = new XMLReader();                    xr.setXML(DBdatabase);                    JOptionPane.showMessageDialog(okButton, "資料庫初始化成功!!!");                    dispose();//                    new LogIn();                    System.out.println("資料庫配置成功進入應用系統!!!");                } catch (SQLException e) {                    JOptionPane.showMessageDialog(okButton, "資料庫初始化失敗!!!"+e);                    e.printStackTrace();                }            }        });        okButton.setBounds(71, 191, 93, 23);        contentPanel.add(okButton);                JButton testButton = new JButton("Test");        /////////////TestButton listener        testButton.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent e) {                DBdatabase = getDatabase();                String dbName = DBdatabase.getName();                DBdatabase.setName("mysql");                ConnectDatabase conn = new ConnectDatabase(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 = new JLabel("Database");        lblNewLabel_1.setHorizontalAlignment(SwingConstants.CENTER);        lblNewLabel_1.setBounds(64, 155, 82, 15);        contentPanel.add(lblNewLabel_1);                databaseName = new JTextField();        databaseName.setBounds(181, 152, 108, 21);        contentPanel.add(databaseName);        databaseName.setColumns(10);            }    @SuppressWarnings("static-access")    public Database getDatabase(){        Database db = new Database();        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){            new JOptionPane().showMessageDialog(okButton, "請完善資料庫資訊!!!");;        }        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);            }        }                    return db;    }    }

設定檔產生程式即把資料庫的相關資訊寫入設定檔供系統之後串連資料庫時讀取,所以這裡組建組態檔案還有一個比較好的好處就是我的程式不需要寫死就是在程式中就需要完全的把資料庫的相關資訊寫進入,這裡我只需要讀取設定檔然後注入到相關的方法中就行。至於設定檔產生器就是先建立一個檔案,然後根據相應的配置資料寫入到檔案中,當然這是一個xml檔案,也可以使用dom4j等來科學的寫入和修改,但這樣比較簡單粗暴,至於xml檔案的解析器和產生器程式在以後的博文中相應的介紹到。

  這個小程式完全是因為自己的小想法和小猜想去實踐寫的並應用到了我的之前的那個資訊管理系統中,以上是小程式所有代碼中一部分,程式完整代碼在我的GitHub中(https://github.com/huangxinyuan650/ConnectDatabase)歡迎大家批評指正

應用程式初次運行資料庫配置小程式(Java版)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.