Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Lab6 Netbeans

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

Lab6 Netbeans

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

LAB 6

Connect from SQL Server Database to Java Application (Query)


Tutorial: Part 1-JAVA MySQL | CRUD Application | Design GUI and Connection
to Database
I. Prerequisites
- Internet connection.
- SQL Database Creation file inside the Lab 6 folder.
o Netbeans IDEA Community Editor at Apache NetBeans Releases
- Database BAK file, SQL Server JDBC Driver, rs2xml Library jar inside the Lab 6 folder.
II. Lab Setup & Guide
1. Set up the Java application project.
- Open IntelliJ IDEA Community, and we get to the Welcome Screen like this.

- Click on New Project, input the project’s Name, Location, Language, and JDK, and
click Create. You may need JDK installed first or let Netbeans IDEA install for you.
- Familiarize yourself with the workspace of NetBeans IDEA. The left sidebar is the
project's directory; the central part is where you code. Also note the Run button, which
will compile your code and Terminal window for debugging purposes.

- Now delete the Main.java class by right-clicking on the file name, then click on Delete
and OK to the pop-up window. We will construct these classes later.
- Lastly, we must import the driver and libraries into the project scope. Right click on
libraries -> Add Jar/Folder to begin the importing process.

- Then click the Libraries tab on the left sidebar and New Project Library -> Java to add
the libraries.
- Point to the JAR libraries inside the Lab 5 folder. Then click OK to add them to the
project. The result should look like this. Then click Apply, OK to finish this step.
2. Set up the Swing UI Form.
- Before we can get to the coding, we need to design the GUI (Graphical User Interface)
Frame to provide a frontend for users to interact with. Right-click the package (pdm06)
folder, then select New -> JFrame Form
- Give the form name and click OK to complete the frame creation.

- Now click the minus button on the sidebar to minimize it and get familiar with the GUI
Design form. The left side has a Component Tree to help you keep track of the
components in the Form and has a default JPanel object as a default. Below is the
property and value key-value pair to modify attributes like name, fonts, size, etc. In the
middle, we have the current frame design preview, and in the rightmost sidebar, we have
a Palette with all the components we need to construct the GUI.
- Here is the list of some standard Java Swing components:
o HSpacer, VSpacer: to add spacing between the elements.
o JPanel: to add a frame for other elements, it must be extended from our frame
classes.
o JButton: add a button with ActionListeners to perform logical code when
clicking (discuss more in the later Lab).
o JScrollPane: add a frame that can be scrollable, especially for extended content.
o JLabel: to add title and instruction on the interface.
o JTextField, JPasswordField: to receive user input on the interface; the latter is
used for the password field to protect privacy.
o JTextArea: to display the message after the query has been done.
o JComboBox: to make a drop-down list for the user to choose from.
o JTable: to display the query result in tabular form.
o JOptionPane: to display the dialog for the user to interact with.
- Drag the corresponding element from the Palette to the main preview frame in the middle
to add a component. Here is an example of adding a JLabel element.

- From then, you must modify its value by double-clicking the Label text in the main
frame, typing new text, and pressing Enter/Return to complete.

- You must also rename the Variable Name component in the code for easy tracking.
Modify it using the property field name and type it in the value box as you want.

- Then, do the same for other components until you get a proper GUI to display to the user.
Design a GUI form as in the Figure below.

3. Set up the helper ConnectSQL.java class.


- Back to the project directory, right-click on the src folder, then New -> Java Class.
- Rename it to ConnectSQL.java and press Enter/Return to complete.

- Examine and copy the code to the file you created, then let IntelliJ IDEA auto-import the
libraries in the code for you.
import net.proteanit.sql.DbUtils;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.sql.*;
import java.util.Vector;

public class Connect {


static final String connectionUrl =
"jdbc:sqlserver:<?>;databaseName=<?>;user=<?>;password=<?>;encrypt=tru
e;trustServerCertificate=true;";

public static void closeConnect(Connection con) {


if (<?>) {
try {
con.close();
} catch (SQLException e) {
System.out.println("Error closing connection");
}
}
}

- Here are some questions for you to consider:


1. Why are most of the variables and functions statically typed?
2. Gather the information and complete the connectionURL string based on your
settings. You need to delete the <?> and fill in your value to it.
3. Can you think of any way to protect the connection string for your application?
Research and give your probable answer.
4. Examine the closeConnect() function and explain the need to use the try-catch block
inside this function. Then, briefly mention why we would need this function in our
code.
- Now, examine these functions, delete the <?> to fill in your value, and then complete the
code.
public static void showQuery(String <?>, JTable resultTable) {
Connection con = null;
PreparedStatement stmt;
ResultSet rs;
try {
con = DriverManager.getConnection(connectionUrl);
stmt = con.prepareStatement(<?>);
rs = stmt.executeQuery();
if (!rs.next())
JOptionPane.showMessageDialog(
null,
<?>,
<?>,
JOptionPane.WARNING_MESSAGE);
else {
resultTable.setModel(DbUtils.resultSetToTableModel(rs));
JOptionPane.showMessageDialog(
null, <?>, <?>, JOptionPane.INFORMATION_MESSAGE);
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(
null, <?>, <?>, JOptionPane.WARNING_MESSAGE);
} finally {
<?>;
}
}

- Use these questions to guide yourself during the code completion:


1. What is a Connection, PreparedStatement, and ResultSet variable type? Find out
some of the methods they provided.
2. Besides executeQuery(), is there any method PreparedStatement provides to perform
the execution query to the database engine?
3. Examine the JOptionPane and type your custom success and failure context for the
user.
4. Fill the appropriate function name to DbUtils to get the queried result formatted as a
table.
5. In the catch block, print out the trace of the catch block to a message dialog.
6. In the final block, use the appropriate function to perform necessary operations after
querying the database.
- Only then should you have completed the Connection.java class. Verify the code is
error-free using IntelliJ IDEA inspection and continue to the other class.
4. Set up the frmMain.java class.
- Now open the file frmMain.java by double-clicking its name on the sidebar, we should
see the code generated by IDEA for us. Modify the generated code to as follow and
replce the <?> with your component name.
-
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class frmMain extends JFrame {


private static frmMain instance;
private JPanel <?>;
private JLabel lblQuery;
private JTextField <?>;
private JTable <?>;
private JButton <?>;

- Copy the following code after the variable initialization lines, then examine and complete
the code by replacing <?> with your answer.
private frmExplorer() {
setContentPane(panel);
setTitle(<?>);
setSize(<?>,<?>);
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.<?>);
}
- Use these questions to guide you:
1. What should be named as the title for this frame?
2. What is the size of this frame window?
3. On close operation, what action should be taken from the WindowConstants class?
- Now it’s time to add an event code for the button. Normally we would right-click the
JButton element, choose Create Listener -> Action Listener, and click OK to finish
the step.
- However, to make the code more robust, we will implement a Design Pattern –
SwingWorker here. Inside the private function frmExplorer(), copy the code below and
complete it by replacing <?> with your answer.
<?>.addActionListener(
e -> {
<?>.setEnabled(false);
if (<?>.getText().<?>) {
JOptionPane.showMessageDialog(
null, <?>, <?>, JOptionPane.WARNING_MESSAGE);
<?>.setEnabled(true);
return;
}
SwingWorker<Void, Void> worker =
new SwingWorker<>() {
@Override
protected Void doInBackground() {
<?>.showQuery(<?>.getText(), <?>);
return null;
}

@Override
protected void done() {
<?>.setEnabled(true);
}
};
worker.execute();
});

- Use these questions to help you complete the code:


1. What is the purpose of the SwingWorker design pattern?
2. Replace the <?> with the named element you set in Step 4.
3. For JOptionPane, replace as you would do in Step 5.
- Complete the function, then add this function and complete this step.
public static synchronized frmMain getInstance() {
if (instance == null) {
instance = new frmMain();
}
return instance;
}
- Now we shall continue to the next step.
5. Set up the Main.java class.
- With the instruction from the above step, create, copy and complete the code for this class
by replacing the <?> part with your answer.
public class Main {
public static void main(String[] args) {
<?>.getInstance().setVisible(<?>);
}
}

III. Lab Task


1. Complete the Java code to build the application. Then, test the database connection
and the application code.
2. Perform these tasks by writing your query and showing the result, given the ERD of
this database.
- Retrieve the subject names taught by a specific teacher with the ID 3.
- Retrieve students' attendance status (present or absent) for a specific lesson with ID 2.
- Retrieve the total number of students enrolled in each subject.
- Retrieve the average length of lessons (in days) for each teacher.
- Retrieve the total number of lessons conducted for each subject.
- Retrieve the maximum and minimum number of students in a lesson across all subjects.
- Retrieve the average number of students absent for each subject across all lessons.
3. Import your project DB then connect it with Java and perform 10 query statements. Write
your questions, your queries and the output.

You might also like