- Making a simple MySQL client in NetBeans - Licence Fondamentale d'Informatique
samedi 1 mars 2014

Making a simple MySQL client in NetBeans

NetBeans has a nice interface to connect DB, but many SQL commands are to be input as a whole sentence I made Swing application for inserting and viewing data to a table of MySQL database. The sample is very simple, available for one specific table and without deleting or updating operation, It would be extended but the document would be longer and more complicated, I'm afraid.

INDEX

Connecting to MySQL database

I expect that the readers already have a suitable environment of MySQL database server working, having a database with an enough grant to a given user. In this sample,
database name: nonidb
user: noniko
password: (blank) 
<- because it's a merely a sample at all. If you have some important data, please set a proper password!
Also, you would get a JDBC driver file for MySQL. I prepared mysql-connector-java-3.1.6-bin.jar file through MySQL developer's web site.
Now, let's go to NetBeans. Click the "Runtime" tab to switch the window you may usually see "Projects" or "Files" window.
Select "Add Driver" in Runtime Window
You will find "Databases" node here. open this node to get "Drivers" node under it. If you open more to show the content of "Drivers", you will find only "JDBC-ODBC". The first thing to do is add MySQL driver. Right-click the "Drivers" node to show context menu and select "Add Driver".
Then the setting window appears.
Find the location of JDBC driver file.
By clicking "Add" button you can search the driver file graphically. As the case above, I prepared D:\nonidata\nb4worksnew folder for contain project folders and lib subfolder to contain library files.
If you select the driver file's location , Driver Class and Name are set automatically. In the case of MySQL JDBC driver, the old class name is set first. but click "Find" button, then the progress bar below became active and finally "Searching for driver classes finished" is shown.
Then open the combo of "Driver Class" setting. you can select the current class name of the JDBC Driver.
Change class name to that of current version.
Click "OK", then the new driver node is added under "Driver" node. Right-click it to select "Connect Using.." from context menu.
Select "Connect Using..." from context menu
The setting window appears. Here Database URL, User Name and Password are needed ( In this case Password is blank).Click OK then you could see "Connection established" message in the progress bar below. The page might be switched to "Advanced", but in this case there is no advanced setting needed.
After the connection established, a node for this connection is appeared. Let's proceed to next step .

Creating a sample table

Right-Click the node for the connection established above, Select "Create Table...".
Select "Create Table" from context menu
Then a window appears for setting the table to create. To display the required setting this window might have to be expanded manually. The important settings are Key, Column name, Data type and Size, depending on the Data type.
Creating a table in NetBeans
In this case I made a sample table "cars" having caridnamevendor and type as fields. the field carid is the primary key. All the fields have data type of VARCHAR. Only carid has 10 for size and all others have 20.
Once the table created, you can see its node under the connection node. The structure of the table "cars" are displayed.
The node tree of the table created

Insert the first data

Now let's insert the first row by sending SQL command. Right-Click any node under the connection node to display "Execute Commands..."menu item.
Then the large window of operating command appears at the same place of source editor. Too large, so I will not show the screenshot of the whole appearance. The important spots are, first of all, the text area for inputting command.
Input a whole command sentence.
Click "Execute" button and, if the command is valid, you can see the "Command successfully excuted" message below. More to make sure, right-click the "cars" node and select "View data".
Right-Click the "cars" node to view data.
First data inserted
Yeah! The first data were successfully inserted. But you might think the whole sentence "insert into..." bothering. I did. So I made up mind to build an application to insert data by more graphical operation.

Creating a new Java Project

Let's create a new Java Project for the application. Select from Menu bar "File"->"New Project". In the new project wizard, select "General"->"Java Application" as the project type. In my case the project name was "mysqloperation" and the location was "d:\nonidata\nb4worksnew\mysqloperation". Check off "create main project".
After creating the project, create new package. In my case, "mysqlop".

Creating a utility class for connecting database

Operation of database in Java is very complicated, requiring connection, statement, resultset and many try&catch. So I used a utility class dealing with such operation.
The whole code is shown here, MyDBConnection.java.
init() method is for connecting MySQL database.
getConnection() method is to be called after init()method, to give to the other class the established connection.
two close() methods and destroy() methods are for settling the end of operation. Closing connection, statement or resultset requires try&catch so they have been extracted here.
To use this file, classpath to the JDBC driver must be set for this project. Right-click the "mysqloperation" project and select "Properties..." from the context menu. In the "Project Properties" window, select "Build"->"Compiling Sources".Click "Add JAR/Folder..." button near the "Classpath for Compiling Source" setting , so you can search the location of the JDBC jar file.
Adding JDBC jar file to classpath

Creating the Table Model

Then I prepared a cusomized Table Model for the JTable to use in this app.
The whole code is shown here, CarTableModel.java.
To write this code I used some nice tools of NetBeans.
First, create a new Java Class file named CarTableModel.java. It has a very plain and empty template, just with package and class declaration.

Edit manually the class declaration to extend "AbstractTableModel" class. The editor soon show the red and waved underline to show errors. One cause of this is lack of importing "javax.swing.table.AbstractTableModel" class. This error is fixed by right-clicking somewhere of the code and select "Fix Imports".
Use "Fix imports" tool
You can check the declaration
import javax.swing.table.AbstractTableModel;
has been inserted near the top of the source code.
But still the red underline remains. The remaining cause of this is lack of implementation of proper abstract methods.
This is fixed by "overriding method" tool invoked this way...
Use "Overrice Methods" tool
The required implementations are extracted checking "Show Abstract Methods Only".
Required implementations are listed
Select all of the three methods by clicking the node and "OK".
Required implementations are inserted automatically
Now the red line is gone!
In fact, we also need to override getColumnName(int param) method, otherwise we couldn't get customized headders of the table.
Let's fill the contents.
The code is specified to access the specific table "cars", so the number of column is fixed to 4.
Each column's name is also known and can be set directly.
This time I used Generics, a new feature of JDK5.0, for the first time. It worked successfully in NB (Clap hands!)

Creating the JFrame Form class-the Form design

Now let's create the JFrame Form Application, The main class of this project! "JFrame Form" can be selected in the new wizard. The name is "InsertTable" in my case, which created a source file "InsertTable.java".
First, design the form. It should be take a vertically long window, so I fixed the form size instead of use "packing".
Select "JFrame" node in the Inspector window to show its properties. Change "Form Size Policy" from default "Generate pack()" to "Generate Resize Code".
To fix the Form size.
Then "Form Size" property becomes editable. Edit it as:
The Form size edited.
This form will be separated vertically into three parts:
(1)JTextfields orJComboBox to input the new data.
(2)JButton to send data and show message.
(3)The JTable.
The first two should be located on eachJPanel, and the JTable on a JScrollPane. This is the basic parts.
JPanels and JScrollPane to locate the components.
Notice the vertical positions of the nodes don't mean their actual locations. I mean, dataPanel, sendPanel and tablePane are located to North, Center and South of BorderLayout, respectively.
On dataPanel, 3JTextFields and one JComboBox to input data and 4JLabels for explanations should be located. I decided GridLayout is the best to set these locations. The default layout onJPanel is FlowLayout in NetBeans. It must be changed:
Change to GridLayout
Then properties of this GridLayout is displayed. Set colunm number to 2, row number to 4.
Then locate the components. they could be moved by drag and drop on the form, If you are not satisfied with the location.
Moving the JComboBox within the GridLayout.
The component might escape to a very wrong position, as a different panel. Don't worry, you can move its location by drag and drop within the Inspector window, too.
Moving the JComboBox within the Inspector window.
After all components are set, customize their name to show their roles.
Also customize text property of each JLabel, and eraze that of each JTextField. Here is an example of editing "text" property of JLabel:
Customizing "text" property to show "ID:"as JLabel
Then sendPanel to locate JButton and and JLabel. Also GridLayout is set for this JPanel, with 1 column and two rows. The name and "text" property are customized.
In this way the components, other than JTable, arearranged as below:
Components without JTable has been customized.

Customizing JTable

As shown above, at this point the JTable has 4x4 structure and empty data. Let's customize it to show the content of the table "cars" of MySQL database.
Select the JTable now is named "carTable" in the Inspector window to show its properties. Find the "model" property and click the "..." button at the right edge .
carTable and its "model" property
Then the editor window appears. The default 4x4 structure is set in this window. Let's change "Select Mode" from "TableModelEditor" to "FormConnection".
Switching from default Table Model Editor to Form Connection mode.
In the Form Connection mode, Click the radio of "User Code" in the option window.
Form Connection mode
Then look at the bottom of this window. The "Advanced" button is there. Click it!
"Advanced" button at the bottom of the window
A window appears to edit before and after the code of setting the TableModel for the JTable. This time check both to edit .
The method named getResultFromCars should be created in the source code of "InsertTable.java" manually like

 public ResultSet getResultFromCars() {
        
        ResultSet rs=null;
        
        try{
            rs=stmt.executeQuery("Select * from cars");
        
        }
        catch(SQLException e){}
        
        return rs;
        
    }
Click OK to return the "User Code" to fill.
Note that here semicolon";" to terminate the sentence SHOUD NOT BE input. Why? check the source code. Check the InitComponents() method. Here!
Light-blue "Protected""Uneditable" area? Who said so? Ho-ho-ho! You can edit frrreely by this means prepared by NetBeans!

First running of InsertTable

To make a first test run of this customized JTable, we still have something to do. First, declaration.
private MyDBConnection mdbc;
private java.sql.Statement stmt;
They are to be written somewhere in the source. Near the EOF, close to other variables, would be nice.
Then the constructor. Note that we should add throw declaration to it
to avoid that annoying compile error "java.sql.SQLException is not reported...".
The whole content of the constructor is :
 
public InsertTable() throws  Exception{
        
         mdbc=new MyDBConnection();
         mdbc.init();
         Connection conn=mdbc.getMyConnection();
         stmt= conn.createStatement();
        
        initComponents();
    }

 
One more to avoid the same compile error. Edit the main method prepared by NetBeans:
Add try-catch to the main method
Now let's run the project! An window to select main class might be appear. In the list you will find only this "InsertTable.class". Select it.
The tabledata of MySQL was shown
The only one row existing in "cars" table of MySQL database has been displayed!

Taking a little care...

Now that we could display existing data from MySQL to JTable, Let's feel settled and take a little care for better application.
One thing is a proper termination of this application, All the sessions with MySQL(connection, statement, resultsets) must be closed.
This application is terminated by closing the window. So we should add an event processing method for WindowClosing event.
Select "JFrame" in the Inspector window to show its properties window, and then click "events" to switch the page. Find "windowClosing" event. It is set to be <none> by default, but when you click the word <none>, it would be changed automatically to "formWindowClosing"...press the Enter key while this row is selected.
Setting windowClosing event of JFrame
Then the source code appears to enable to edit the method.
Edit "formWindowClosing" method
Close the statement and the connection.
The other thing is to set items of the JComboBox named typeCombo. Yes, it should be equipped to select drive type of a car.
Select "typeCombo" node in the Inspector Window to show its properties. Find "model" property and click "..." button on the right edge, just like we did for setting the TableModel for JTable.
A window appears, This time we use the default ComboBoxModelEditor.
Input a new item in "Item:" field and click "Add" button. That's easy! I prepared the items "FF", "FR", "MR" and"4WD" as drive type. Are there anything else?

Inserting data to MySQL

The finishing spurt! Inserting data to MySQL should be done at the clicking "Send" button(the JButton named "sendButton").
In NetBeans' GUI Editor, it's very easy to make event processing method for JButton. Just double-click the JButton itself on the form.
The "sendButtonActionPerformed" method is created in the source file. Let's fill the content as this:
private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendButtonActionPerformed
        // TODO add your handling code here:
        
        String carid=idField.getText();
        String name=nameField.getText();        
        String vendor=vendorField.getText();
        String type=(String)typeCombo.getSelectedItem();
        
        String insertStr="";
        
        try{
            
            insertStr="insert into cars (carid, name, vendor, type) values("
                    +quotate(carid)+","
                    +quotate(name)+","
                    +quotate(vendor)+","
                    +quotate(type)
                    +")";
            
            int done=stmt.executeUpdate(insertStr);
            
            commentLabel.setText("1 row inserted");
           
            getContentPane().removeAll();
            initComponents();
        
        }
        catch(Exception e){
            commentLabel.setText("Error occurred in inserting data");
            e.printStackTrace();
        }
        
    }//GEN-LAST:event_sendButtonActionPerformed
Note that initComponents method is called after inserting data, and after removing the current comtent pane.It's necessary to refresh the JTable's appearance...If I were skilled more, I could refresh only JTable, instead of the whole container. This is, as is called in Japanese a way like "Chopping tofu with the axe". Sorry!
Also note here the quotate method is called. I created it not to hit so many quotation marks:
 public String quotate(String content){
    
        return "'"+content+"'";
    }

Now the whole code for InsertTable.java.
Run the project! Input data and click the "Send" button. Now you can see another row just inserted in the JTable. Repeat inserting a few more!
Operating the completed application
...And let's make sure these data will be viewed also from NetBeans' utility.
Tough work! But through this project we have learned:
  • How to operate database from NetBeans's utility
  • How to edit the "protected" codes in the light-blue area
  • How to use customized TableModel for JTable
...and so on.

0 commentaires:

Enregistrer un commentaire

 
-