0% found this document useful (0 votes)
55 views

PRYMSQL2

This document summarizes steps for creating a Java program in NetBeans that connects to a MySQL database: 1. A new Java project is created and a utility class is made to handle database connections. 2. A JFrame form is designed with input fields, buttons, and a JTable to display database records. 3. The JTable is customized to display data from the MySQL "cars" table by setting its table model. 4. Code is added to connect to the database and populate the JTable, allowing the first test run of the program.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views

PRYMSQL2

This document summarizes steps for creating a Java program in NetBeans that connects to a MySQL database: 1. A new Java project is created and a utility class is made to handle database connections. 2. A JFrame form is designed with input fields, buttons, and a JTable to display database records. 3. The JTable is customized to display data from the MySQL "cars" table by setting its table model. 4. Code is added to connect to the database and populate the JTable, allowing the first test run of the program.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

PRACTICA PARA REALIZAR UN PROGRAMA EN NETBEANS RELACIONADO CON UNA

BASE DE DATOS EN MYSQL

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.
package empleado;
import java.sql.*;
public class MyDBConnection {
private Connection myConnection;
/** Creates a new instance of MyDBConnection */
public MyDBConnection() {
}
public void init(){
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
myConnection=DriverManager.getConnection(
"jdbc:mysql://Localhost/diana","root", ""
);
}
catch(Exception e){
System.out.println("Failed to get connection");
e.printStackTrace();
}
}
public Connection getMyConnection(){
return myConnection;
}
public void close(ResultSet rs){
if(rs !=null){
try{
rs.close();
}
catch(Exception e){}
}
}
public void close(java.sql.Statement stmt){
if(stmt !=null){
try{
stmt.close();
}
catch(Exception e){}
}
}

public void destroy(){


if(myConnection !=null){
try{
myConnection.close();
}
catch(Exception e){}
}
}
}
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.
package empleado;
import javax.swing.table.AbstractTableModel;
import java.sql.*;
import java.util.ArrayList;
public class tabla extends AbstractTableModel {
private int colnum=2;
private int rownum;
private String[] colNames={
"cedula","nombre"
};
private ArrayList<String[]> ResultSets;
/** Creates a new instance of FoodTableModel */
public tabla(ResultSet rs) {

ResultSets=new ArrayList<String[]>();

try{
while(rs.next()){

String[] row={
rs.getString("cedula"),rs.getString("nombre")

};
ResultSets.add(row);

}
}
catch(Exception e){
System.out.println("Exception in CarTableModel");
}
}
public Object getValueAt(int rowindex, int columnindex) {
String[] row=ResultSets.get(rowindex);
return row[columnindex];
}
public int getRowCount() {
return ResultSets.size();
}
public int getColumnCount() {
return colnum;
}
public String getColumnName(int param) {
return colNames[param];
}
}
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.
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.
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!

You might also like