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

Java GUI Programming With MySQL

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Java GUI Programming With MySQL

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Java GUI Programming with MySQL

This tutorial will show you how to connect to a database server (MySQL) and retrieve information to put into an GUI (Table,
Combo Box etc…) in JAVA. We will use Netbeans IDE.

Before we will start coding with our GUI, let’s first setup our database server. Download and Install WAMP(Windows, Apache,
MySQL, PHP) at http://www.wampserver.com/en/. It is a program bundled with a web server with PHP and MySQL, it is a
complete package for developing a website with a database, but we are not going to use the web server here, just the database
server (MySQL).

Once you have download and installed Wamp according to your computer architecture (32bit/64bit), Click Start then search for
wamp then click on WampServer64 (my computer is 64bit).

Now on your Taskbar, look for the Wamp icon (Red) then click on, on the popup, click on Start all services.

Once the Wamp icon turns Green, it means all services have successfully started (Web server & Database server). Now open a
web browser then visit http://localhost/phpmyadmin/ it will open a web browser and will show you PHPmyadmin, it is a web GUI
for controlling your database server.

On the login screen, login as username root with no password, it is the default on freshly installed wamp.
It will bring you to this page:

Where we will create a new database where we will retrieve our data. Let’s create our database for students.
Clicks on the database tab, then on the database name text field, type in students_db then click on create.

You can see your new database on the left side of the screen:
Now our database will consists of tables, this tables holds a group data, you can have many tables in one database. Table names
are named according to the data they hold.

Let’s create a student table to hold our student records. Click on the database then on the right side under the Structure tab
create a table students with 5 columns. The columns are fields which consist of the data per row will hold.

Now it will bring you to the table field page. Here is where we define our fields, for now, our students will hold a data for their
student id, first name, last name, gender and section.

Type in and follow the screen on the screen shot:

As you can see, student_id field will have a datatype of INT (Integer) with the index of PRIMARY and is A_I (Auto Increment).

Let me explain: PRIMARY INDEX or PRIMARY KEY means that the field must be unique among all rows, so no two rows will have
the same value of the field. Since each students will have different ids then it will be declared as a PRIMARY KEY. The A_I (AUTO
INCREMENT) means that each new row inserted will have a value of an incremented value of the last row inserted; let’s say the
last row was having a student id of 3, so the row next inserted will have a value of 4. We have set it that way because will have a
unique value each time a row is inserted.

Now our fields last_name, first_name, gender and section have a data type of VARCHAR(Variable Character) which can hold text
or numbers with a determined length, our first and last names will have a max length of 250, gender 6 (Male or Female) and
section of 250. If a row inserted with a value exceeding the length, the value would be truncated, for example the length of a field
is 3, then the value inserted was “FOUR” then it would be truncated and will be “FOU” instead of “FOUR”.

Ok once you have typed all the fields, click on the save button.

Now let’s create another table Sections with the fields section id and section name:

Now click on save and it will create the sections table.

Once it is created, let’s insert some rows in our sections table, it will be used later in the program. Click on the sections table then
click on the insert tab.

Here is where we insert rows using a GUI. Now insert the following sections:

Grade 8 – I
Grade 8 – II
Grade 8 – III

You can leave the section_id field empty since it is an auto increment field

After that click on Go.

To view our inserted rows, click on the Browse Tab of our sections table.
Ok now we are done will our database. It is time to create our GUI.

To start off, open Netbeans and create a new project.


Click File>New Project>Java>Java Application then Click Next.
Our project name would be GUI. Uncheck the Create Main Class then click Finish.

After that you would see our project create the Project window on the Left Side of the screen.

Now let’s create JFrame Form, here is where we put our GUI elements.

Right-click on the default package then select New>JFrame Form, Our form name would be Students then click on Finish.

Now let’s drag in some elements to our form, on the Palette window on the right-side is where all available GUI elements shown,
you can simple drag and drop GUI elements from the Palette window.
First let’s put a Table element under the Swing Controls elements. We will populate this table with our students table from our
database.

Let’s change our table columns according to our table in our database. Right click on our table and click on Table Contents…

A Customizer Dialog window will be shown, first we will delete the Rows since will retrieve the rows from our database. On the
rows tab, highlight all our rows then click on delete.
Now let’s define the columns, since our database have 5 columns then our table should also have 5 columns. Click the columns
tab and insert 5 columns:

Now let’s the column name and type according to our database table, and uncheck the Editable so it can’t be edited:

As you can see here, the Students ID columns has a type of integer since in our database, it was a INT data type. The Last Name,
First Name, Gender and Section has a type of String, since VARCHAR accepts any text. Now click on close:
Ok now it done, let’s name our table as students_table.
Right click on our table then click on properties.

Click on the code button, then under the variable name, type in students_table:

Ok once it’s done, let’s create a some text fields and some buttons where a user can add, update, and delete:

Create something similar:


After that, set the names of the text fields and button appropriately.

For the first name text field, the name would be first_name_tf
For the last name text field, the name would be last_name_tf
For the gender combo box, the name would be gender_cb
For the section combo box, the name would be section_cb
For the add button, the name would be add_btn
For the uodate button, the name would be update_btn
For the delete button, the name would be delete_btn

Now let set the values of the combo box for our Gender Combo box:

Right-click our gender combo box then select properties, under the properties tab, look under properties section then model
properties, then click the “…” button:
Each item of our gender combo box is separated by a new line, since we have only two genders: Male and Female, edit the text
field then type in:

Male
Female

Now click on the OK then close.

Let’s also edit the values for our section combo box; this time set the values to empty since we will retrieve the values of our
section combo box from our database:
Ok now we are done with our GUI, let’s add some functionalities:

First thing we want to do is populate our sections combo box and students table with data from our database when the form
loads.

Since the students table is still empty, then let’s first populate the section combo box.

First let’s add an Event Listener when our form window opens. Right-click on our form then choose
Events>Window>windowOpened.

Once done, you will be in the source view; this would create a function that will be executed when our form opens:
To test it out, let’s put a simple string output from our Output console:

Now click on the Run button:


Ok now let’s put in some code to connect to our database:

When we connect to MySQL, the connection is handled by a driver. For JAVA, the driver is called MySQL JDBC Driver. Let’s first
add the driver, to do that, on our the Project window, right click on Libraries then click Add Library:

On the Add Library Window, look for MySQL JDBC Driver, then click Add Library:

Ok once done, let’s add some code on our window open function:

try {
Driver mySqlDriver = (Driver) DriverManager.getDriver("jdbc:mysql://localhost:3306/");
Properties prop = new Properties();
prop.put("user", "root");
prop.put("password", "");
Connection con = (Connection) mySqlDriver.connect("jdbc:mysql://localhost:3306/students_db", prop);
System.out.println("Connected to database!");
} catch (Exception e) {
System.err.println(e.getMessage());
}
Let me explain the code:

As you can see our code is inside a try and catch block

try{
Code…
}catch(Exception e){
Error…
}

That’s because the code inside the try block will be throwing some errors, like when it will failed to connect to the database then
it will execute the code in the catch block.

Now I’ll explain each line of code in the try block.

Before we can connect to our database, we need first a driver to handle our connection, so we need to instantiate a driver.

Driver mySqlDriver = DriverManager.getDriver("jdbc:mysql://localhost:3306/students_db");

This line set the variable mySqlDriver as our driver, it will get the driver from the DriverManager.getDriver() method. The method
requires a string as a argument, this string is also known as a Connection String. Each database has its own connection string
syntax. So for our database server, the syntax of the connection string would be:

"jdbc:mysql://localhost:3306/students_db"

The noted words here are localhost:3306 and students_db, which mean the drivers manager will try to connect to the local
machine (localhost/127.0.0.1) at port 3306, this port is where MySQL listens for connections, and the students_db is the name of
our database.

Once you’ll have a mysql driver instance, we can now connect to the database using the syntax:

Driver_Instance.connect(connectionString, properties);

In here, the driver instance Driver_Instance variable will have a method connect and accepts a valid connection string and
properties. So in our case, since our variable name was mySqlDriver, then our syntax would be:

mySqlDriver.connect("jdbc:mysql://localhost:3306/students_db", prop);

But as you can see, the method needs some properties. These properties are the login properties for mysql, since earlier we used
the username root and with no password to login to phpmyadmin, it was actually login in to mysql.

So for creating a properties instance we instance it:

Properties prop = new Properties();

Then add some properties using the Put method:


prop.put("user", "root");
prop.put("password", "");

Now the we have a property variable we can now put it in the connect method of the driver:

Connection con = (Connection) mySqlDriver.connect("jdbc:mysql://localhost:3306/students_db", prop);

Note: The con variable will hold our connection, the (Connection) is used to cast the value of our connect method as a
Connection instance, since the connect method will return a connection.

Final syntax:

Driver mySqlDriver = DriverManager.getDriver("jdbc:mysql://localhost:3306/students_db");


Properties prop = new Properties();
prop.put("user", "root");
prop.put("password", "");
Connection con = (Connection) mySqlDriver.connect("jdbc:mysql://localhost:3306/students_db", prop);

Now Add:

System.out.println("Connected to database!");

After setting the connection to the con variable to check if no errors occurred after trying to connecting.

Now let’s try to run our program:

After that is done. We can now start retrieving rows from our database.

Since we are going to fill up the sections combo box with rows from the sections table, the we must execute a SQL (Structure
Query Language) query. This will give us row according to the query.

So the query for retrieving all the rows from our sections table would be:

SELECT * FROM sections

But where do we write the query string? We must first instance a prepared statement, prepare statement ensures a safe and
secure query execution. To do that the syntax would be:

PreparedStatement ps = (PreparedStatement) con.prepareStatement("SELECT * FROM sections");

From our con variable, we used the prepareStatement method. The methods accept a SQL query string.

Ok now that we have prepared our statement (sql statement), then we are read to execute the query using the executeQuery
method. This method will return a result set if the table has row. So we must create a variable with the type of ResultSet:

ResultSet rs = ps.executeQuery();

Now the rows from our database are now at the Result set variable rs.

We can now loop through the ResultSet using the syntax:

while(rs.next()){
System.out.println(rs.getObject("section_name"));
}

The rs.next() method will return true if there is a next row from the cursor, the cursor is always set to the first row upon
executing.
The rs.getObject(string) method accepts a string which is a column name from our database and will return the VALUE of the
field.

The string is the name of the column.

Final Syntax:

PreparedStatement ps = (PreparedStatement) con.prepareStatement("SELECT * FROM sections");


ResultSet rs = ps.executeQuery();
while(rs.next()){
System.out.println(rs.getObject("section_name"));
}

Now run the program:

Now we want this values to be added to our combo box using add addItem method.

Since the variable name of our sections combo box is section_cb then we can add a new Item using:

section_cb.addItem(string);

now we just add this inside our while loop, and replace the string as the column object.

String section_name = rs.getObject(“section_name”).toString();


sections_cb.addItem(section_name);

Final loop:

while(rs.next()){
String section_name = rs.getObject("section_name").toString();
section_cb.addItem(section_name);
System.out.println(rs.getObject("section_name"));
}

Now run our program:


Ok now that we are done populating our sections combo box, we are now going to add some functionalities to the add button.

First we must add a Click Event Listener to our add button, to do that, click on the design tab to switch to design view, then right
click on the add button, chose Events>Mouse>mouseClicked
Since we are going add a new student, in mysql, “adding” is Inserting a new row. To insert a new row, we execute an INSERT
QUERY:

INSERT INTO tablename (columns) VALUES (values)

The (column) is where the columns of the table will be, they must be comma separated; and the values are relative to the
columns specified between the open and close parenthesis.

So our query would be:

INSERT INTO students (last_name, first_name, gender, section) VALUES (?, ?, ?, ?);

Notice that the values are question marks (?), that’s because they will serve as a place holder for a value that will be specified
later in the prepareStatement.

So the syntax of our prepared statement would be:

String insertQuery = "INSERT INTO students (last_name, first_name, gender, section) VALUES (?, ?, ?, ?)";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(insertQuery);

So let’s just copy the connection from the window open method since we need to connect to the database to execute a query.

Then just the copy the current syntax we have for inserting:

Ok now let’s set the values for our place holders. To set the values, we use the set<DataType>() method.

Since our last_name, first_name, gender and section are VARCHAR fields, they are considered as strings in java.

So we use the setString(index, string) method, where the index corresponds with the place holder

1 2 3 4
(?, ?, ?, ?)

The first question mark will have an index of 1, second question mark 2 and so on, the first question mark will hold the value for
the last_name, the second question mark will hold the value for the first_name and so on

(last_name, first_name, gender, section) VALUES (?, ?, ?, ?);

So now let’s set the 1st index, this will hold the value of the last name, since we want to get the value from our text field
last_name_tf, We can use the getText method.

last_name_tf.getText();

Then let’s set the first index as last_name.tf.getText();

ps.setString(1, last_name_tf.getText());

Now do the same for the first_name, but this time, at the second index:
ps.setString(2, first_name_tf.getText());

Now our 3 index should hold the gender, to get the value from our combo box. To get the current selected item, we use the
getSelectedItem() method,

String gender = gender_cb.getSelectedItem().toString();

Since the getSelectedItem returns an object, then we need to convert it into a string using the .toString() method.

Now set the value for our 3rd index:

String gender = gender_cb.getSelectedItem().toString();


ps.setString(3, gender);

Now do the same for the sections combo box since it is a combo box:

String section = section_cb.getSelectedItem().toString();


ps.setString(4, section);

Now lastly we execute the function, but this time we use the execute() method instead of the executeQuery() method, because
we are inserting, we don’t expect any rows returned, that’s why we use the execute() method, which returns true if the query was
successful.

ps.execute();

Full Syntax:

Driver mySqlDriver = (Driver) DriverManager.getDriver("jdbc:mysql://localhost:3306/students_db");


Properties prop = new Properties();
prop.put("user", "root");
prop.put("password", "");
Connection con = (Connection) mySqlDriver.connect("jdbc:mysql://localhost:3306/students_db", prop);
System.out.println("Connected to database!");

//INSERT statement
String insertQuery = "INSERT INTO students (last_name, first_name, gender, section) VALUES (?, ?, ?, ?)";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(insertQuery);

ps.setString(1, last_name_tf.getText());
ps.setString(2, first_name_tf.getText());

String gender = gender_cb.getSelectedItem().toString();


ps.setString(3, gender);
String section = section_cb.getSelectedItem().toString();
ps.setString(4, section);

ps.execute();
System.out.println("Added to database");
Notice that I have put and print statement after the execution, to check that the execution was successful.

Now run and test the program:

Our database:

Ok now that we have a student in our database, let’s us now try to display it on our table.

The process would be the same like the one we added items earlier on the combo box, but instead of adding into a combo box,
we’ll be adding to a table.

Ok first we connect to the database:

try {
Driver mySqlDriver = (Driver) DriverManager.getDriver("jdbc:mysql://localhost:3306/students_db");
Properties prop = new Properties();
prop.put("user", "root");
prop.put("password", "");
Connection con = (Connection) mySqlDriver.connect("jdbc:mysql://localhost:3306/students_db", prop);
System.out.println("Connected to database!");

} catch (Exception e) {
System.err.println(e.getMessage());
}

Then we perform a query that would get all students in the database::

SELECT * FROM students

//Get Students from database


PreparedStatement ps = (PreparedStatement) con.prepareStatement("SELECT * FROM students");
ResultSet rs = ps.executeQuery();

Once done, we loop through the record set

while(rs.next()){
//Add rows to table
}

So inside the while loop we want to add rows to the table.

So to add rows; first we must get DefaultTableModel of our student table.

DefaultTableModel dtm = (DefaultTableModel) students_table.getModel();

Remember the combo box model?

We added items using that, so similarly to the table, we add rows using its Model.

We can add rows using the .addRow(Object) method.

So our code would be something like:

while(rs.next()){
dtm.addRow(Object);
}

Now the addRow method requires and Object to be passed it, this Object should be an array of Object. An instance of a class is
called an Object. So Object array is a general type of array, meaning any data type can be put it this array.
So first we need to instantiate an array of Object. Why an array? Because each index of the object array correspond to a column in
the table, so index 0 would be the first column in our table. Since we have 5 columns, so our array should have a length of 5:

Object[] row = new Object[5];

Ok now that we have our object, let’s set the proper values for each index (columns);

row[0] – Student ID
row[1] – Last Name
row[2] – First Name
row[3] – Gender
row[4] – Section

So the first row should have the Student ID, since in our database, the data type of our ID was INT, so we retrieve this value as
rs.getInt(column);

while(rs.next()){
Object[] row = new Object[5];

row[0] = rs.getInt(“student_id”);
dtm.addRow(Object);
}

Now since all other 4 columns are type of VARCHAR, then we get them using rs.getString(column);

while(rs.next()){
Object[] row = new Object[5];

row[0] = rs.getInt(“student_id”);
row[1] = rs.getString (“last_name”);
dtm.addRow(Object);
}

Now do the rest:

while(rs.next()){
Object[] row = new Object[5];

row[0] = rs.getInt(“student_id”);
row[1] = rs.getString (“last_name”);
row[2] = rs.getString (“first_name”);
row[3] = rs.getString (“gender”);
row[4] = rs.getString (“last_name”);

dtm.addRow(Object);
}

Since we are keep adding rows to the table, before we add rows, let’s make sure that it is clear of rows first, to clear the rows, we
use the .setRowCount(int); method, This sets the row according to the passed integer, so if we pass in 0, the rows would be 0 or
no rows.

So:

dtm.setRowCount(0);

while(rs.next()){
Object[] row = new Object[5];

row[0] = rs.getInt(“student_id”);
row[1] = rs.getString (“last_name”);
row[2] = rs.getString (“first_name”);
row[3] = rs.getString (“gender”);
row[4] = rs.getString (“last_name”);

dtm.addRow(Object);
}

Final Code:

try {
Driver mySqlDriver = (Driver) DriverManager.getDriver("jdbc:mysql://localhost:3306/students_db");
Properties prop = new Properties();
prop.put("user", "root");
prop.put("password", "");
Connection con = (Connection) mySqlDriver.connect("jdbc:mysql://localhost:3306/students_db", prop);
System.out.println("Connected to database!");

//Get Students from database


PreparedStatement ps = (PreparedStatement) con.prepareStatement("SELECT * FROM students");
ResultSet rs = ps.executeQuery();

DefaultTableModel dtm = (DefaultTableModel) students_table.getModel();

dtm.setRowCount(0);

while(rs.next()){
Object[] row = new Object[5];

row[0] = rs.getInt("student_id");
row[1] = rs.getString("last_name");
row[2] = rs.getString("first_name");
row[3] = rs.getString("gender");
row[4] = rs.getString("section");

dtm.addRow(row);
}

System.out.println("Students Retrieved");
} catch (Exception e) {
System.err.println(e.getMessage());
}

Ok since this we clear and add new rows to our table, it is like refresh the table, so we may also like to add this code after adding a
new student to refresh the table, but that’s a long code, so we may want to put this inside a function

private void refreshStudentsTable(){


try {
Driver mySqlDriver = (Driver) DriverManager.getDriver("jdbc:mysql://localhost:3306/students_db");
Properties prop = new Properties();
prop.put("user", "root");
prop.put("password", "");
Connection con = (Connection) mySqlDriver.connect("jdbc:mysql://localhost:3306/students_db", prop);
System.out.println("Connected to database!");

//Get Students from database


PreparedStatement ps = (PreparedStatement) con.prepareStatement("SELECT * FROM students");
ResultSet rs = ps.executeQuery();

DefaultTableModel dtm = (DefaultTableModel) students_table.getModel();

dtm.setRowCount(0);

while(rs.next()){
Object[] row = new Object[5];

row[0] = rs.getInt("student_id");
row[1] = rs.getString("last_name");
row[2] = rs.getString("first_name");
row[3] = rs.getString("gender");
row[4] = rs.getString("section");

dtm.addRow(row);
}
System.out.println("Students Retrieved");
} catch (Exception e) {
System.err.println(e.getMessage());
}
}

SEARCH

refreshStudentsTable()

PreparedStatement ps = (PreparedStatement) con.prepareStatement("SELECT * FROM students WHERE last_name LIKE ? OR


first_name LIKE ? OR gender LIKE ? OR section LIKE ?");

ps.setString(1, "%"+searchTf.getText()+"%");
ps.setString(2, "%"+searchTf.getText()+"%");
ps.setString(3, "%"+searchTf.getText()+"%");
ps.setString(4, "%"+searchTf.getText()+"%");

refreshStudentsTable(); - searchBtn

Then call the function after Adding and when the window opens.
Ok let’s try out our program:

Ok now that we have successfully retrieved the rows from our database, let us now delete some rows.

Now we want to delete rows when we have selected a row in our students_table and have clicked the delete button.

But since we can select multiple items, then let’s restrict the selection by only by a single row at a time.

To do that, right-click on our students_table then select properties.

On the properties tab, look for the selectionModel then change it’s value to Single selection.
Then click close.

Ok now that we have set single selection only, we now set the mouse click event on our delete button

Ok to delete row the query would be.

DELETE FROM students

This query would delete all the students from our database. But we wouldn’t like that, we want to filter the deletion of students in
correspond with the selection of a row in or students table (the students table in java not in mysql).

So to filter out the deletion, we can add a WHERE statement.

DELETE FROM students WHERE ...

Now what comes after the WHERE? After the WHERE word, the next would be the conditional statement.

DELETE FROM students WHERE first_name = “Pedro”

So this would delete ALL STUDENTS whose name is “Pedro”.

So deleting students by first_name or last_name wouldn’t filter out the deletion, because first names and last names CAN BE
THE SAME.

So what we want is to delete students by using something unique between each student’s.
Since our student_id field is unique to each students, so we can use this field to filter out the deletion.

DELETE FROM students WHERE student_id = ?

Now that we have our query, we can now delete some rows. So we want to delete rows according to the selected row in our
students_table.

Ok if we have selected a row in our students table(java table) we can retrieve the selected row’s index by using the
getSelectedRow() method.

So if I selected the first row:


I would have index 0. If no rows were selected, then the method returns a value of -1.

But we wouldn’t like the index; we would like the take the row’s column data, specifically the student_id, to be used in our
deletion query.

Ok to get the row’s Student ID column value, we can use the method getValueAt(rowIndex, columnIndex); method. The method
accepts two arguments, the first is the row index in which what row are we going to get the column data, and the second
argument, is the column index, which what column we would like to get data.

Since the we can get the current selected row by the getSelectedRow() method, then we can pass this on the first argument, but
before that, let’s check if
DELETE
int index = students_table.getSelectedRow();
int index = students_table.getSelectedRow();
int student_id = 0;
if(index != -1){
int dialogResult = JOptionPane.showConfirmDialog(null, "Delete this student?");
if(dialogResult == JOptionPane.YES_OPTION){
student_id = (int)students_table.getValueAt(index, 0);
try {
Driver mySqlDriver = (Driver) DriverManager.getDriver("jdbc:mysql://localhost:3306/students_db");
Properties prop = new Properties();
prop.put("user", "root");
prop.put("password", "");
Connection con = (Connection) mySqlDriver.connect("jdbc:mysql://localhost:3306/students_db", prop);
System.out.println("Connected to database!");

//DELETE statement
String deleteQuery = "DELETE FROM students WHERE student_id = ?";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(deleteQuery);

ps.setInt(1, student_id);
ps.execute();

System.out.println("Deleted!");
refreshStudentsTable();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}

UPDATE

int index = students_table.getSelectedRow();


//if the row still exists then continue
if(index != -1){
try {
Driver mySqlDriver = (Driver) DriverManager.getDriver("jdbc:mysql://localhost:3306/students_db");
Properties prop = new Properties();
prop.put("user", "root");
prop.put("password", "");
Connection con = (Connection) mySqlDriver.connect("jdbc:mysql://localhost:3306/students_db", prop);
System.out.println("Connected to database!");

//UPDATE STATEMENT
String insertQuery = "UPDATE students SET last_name = ?, first_name = ?, gender = ?, section = ? WHERE student_id =
?";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(insertQuery);

//Set the values of the query according to the textfield and combo box
ps.setString(1, last_name_tf.getText());
ps.setString(2, first_name_tf.getText());

String gender = gender_cb.getSelectedItem().toString();


ps.setString(3, gender);
String section = section_cb.getSelectedItem().toString();
ps.setString(4, section);

//get the student id


String student_id = students_table.getValueAt(index, 0).toString();

//since student id field is an Int, then convert student id to int;

int student_id_int = Integer.valueOf(student_id);


ps.setInt(5, student_id_int);

ps.execute();
//show message that record was updated
JOptionPane.showMessageDialog(this, "Record Updated!");

//clear the textfields


last_name_tf.setText("");
first_name_tf.setText("");
//set the combo box selected item to the first item
gender_cb.setSelectedIndex(0);
section_cb.setSelectedIndex(0);

refreshStudentsTable();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}

SEARCH

private void refreshStudentsTable(){


try {
Driver mySqlDriver = (Driver) DriverManager.getDriver("jdbc:mysql://localhost:3306/students_db");
Properties prop = new Properties();
prop.put("user", "root");
prop.put("password", "");
Connection con = (Connection) mySqlDriver.connect("jdbc:mysql://localhost:3306/students_db", prop);
System.out.println("Connected to database!");

//Get Students from database


PreparedStatement ps = (PreparedStatement) con.prepareStatement("SELECT * FROM students WHERE last_name LIKE ?
OR first_name LIKE ? OR gender LIKE ? OR section LIKE ?");

ps.setString(1, "%"+searchTf.getText()+"%");
ps.setString(2, "%"+searchTf.getText()+"%");
ps.setString(3, "%"+searchTf.getText()+"%");
ps.setString(4, "%"+searchTf.getText()+"%");

ResultSet rs = ps.executeQuery();

DefaultTableModel dtm = (DefaultTableModel) students_table.getModel();

dtm.setRowCount(0);

while(rs.next()){
Object[] row = new Object[5];

row[0] = rs.getInt("student_id");
row[1] = rs.getString("last_name");
row[2] = rs.getString("first_name");
row[3] = rs.getString("gender");
row[4] = rs.getString("section");

dtm.addRow(row);
}

System.out.println("Students Retrieved");
} catch (Exception e) {
System.err.println(e.getMessage());
}
}

private void searchBtnMouseClicked(java.awt.event.MouseEvent evt) {


refreshStudentsTable();
}

You might also like