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

Java Program Development

Uploaded by

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

Java Program Development

Uploaded by

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

Java Program;

Development:
User and
Authentication
Database
A database is a structured collection of
data that is organized in a way that
allows for efficient storage, retrieval,
manipulation, and management of
information. It acts as a centralized
repository where data can be stored,
accessed, and updated by authorized
users or applications.
Database
Examples of popular DBMS include MySQL,
PostgreSQL, Oracle Database, Microsoft SQL Server,
and MongoDB.

In the ever-expanding digital landscape of the 21st


century, databases stand as the unsung heroes, quietly
but indispensably shaping the world around us. From
the moment we wake up to the time we retire for the
night, databases silently orchestrate countless aspects
of our daily lives, often without us even realizing it.
Database
Examples of popular DBMS include MySQL, PostgreSQL,
Oracle Database, Microsoft SQL Server, and MongoDB.

In the ever-expanding digital landscape of the 21st century,


databases stand as the unsung heroes, quietly but
indispensably shaping the world around us. From the
moment we wake up to the time we retire for the night,
databases silently orchestrate countless aspects of our
daily lives, often without us even realizing it.

But why exactly do we need databases, and what makes them so


crucial?
1. Efficient Data Management

1.Imagine a world without databases—a


chaotic realm where information is
scattered like leaves in the wind.
Databases provide structure and
organization to vast amounts of data,
allowing us to store, retrieve, and manage
information with remarkable efficiency.
2. Data Accessibility and Integrity

One of the key features of databases is their


ability to provide quick and easy access to
relevant information while ensuring data
integrity. With a well-designed database system,
authorized users can retrieve the exact data they
need within seconds, eliminating the need for
manual searching through mountains of
paperwork or digital clutter.
3. Scalability and Flexibility
As our digital footprint continues to expand
exponentially, the need for scalable and
flexible data storage solutions becomes
increasingly critical. Databases offer
scalability, allowing organizations to
seamlessly handle growing volumes of data
without sacrificing performance or
reliability.
4. Decision Making and Flexibility
In today's data-driven world, the ability to derive
meaningful insights from vast amounts of data is
paramount. Databases play a crucial role in enabling
data analytics and business intelligence by providing
a centralized repository where data can be
aggregated, analyzed, and transformed into
actionable insights. Whether it's identifying market
trends, predicting customer behavior, or optimizing
business operations, databases serve as the
foundation for informed decision-making and
strategic planning.
5. Security and Compliance
With data breaches and cyber threats on
the rise, data security and compliance have
become top priorities for organizations
across all industries. Databases offer robust
security features, including access controls,
encryption, and auditing, to safeguard
sensitive information against unauthorized
access or malicious attacks.
Requirements To Get Started
XAMPP is a free and open-source cross-platform web
server solution stack package developed by Apache
Friends. XAMPP is designed to be an easy-to-install and
convenient way to set up a local development
environment for web development and testing
purposes. It includes all the components needed to run
a web server on a local machine, making it popular
among developers for building and testing dynamic web
applications offline before deploying them to a live
server.
Download Link: https://www.apachefriends.org/download.html
MYSQL Java Connector
Java MySQL connector is to facilitate
communication between a Java application and a
MySQL database. MySQL is a popular open-
source relational database management system,
and Java is a widely used programming language.
MYSQL Java Connector
The Java MySQL connector, often referred to as
MySQL JDBC (Java Database Connectivity)
driver, allows Java applications to connect to a
MySQL database, execute SQL queries, and
manipulate data stored in the database. It acts as
a bridge between the Java application and the
MySQL database server, providing the necessary
functionality to establish connections, send
queries, and process results.
Download Link: https://dev.mysql.com/downloads/connector/j/
Choose PLATFORM INDEPENDENT.
Then download Platform Independent (Architecture Independent), ZIP
Archive
Once downloaded extract mysql-connector-j-8.3.0
Now we’ve downloaded the necessary requirements, let’s get started!
Create a New Project, do not forget to select Java with Ant > Java Application.
Type the Project name, I used studentInformationSystem.
Under Source Package, right click on <default package>, New> JFrame Form
We’ll begin creating a Registration Form, name the class as Registration then click
Finish.
Once created you will see this on your screen.
Here we’ll see three different tabs in the toolbar:

Source View: this is a text-based editor where developers can


directly view and edit the source code of their projects.
Design View: provides a graphical user interface (GUI) for
designing user interfaces (UI) or visually editing certain types of
files.
History View: allows developers to view and manage the version
history of their project files. It displays a timeline of changes made
to the project, including modifications, additions, deletions, and
commits.

On the right side we’ll see the Component Palette a graphical tool
that provides developers with a convenient way to access and use
various user interface (UI) components when designing graphical
user interfaces (GUI) for their Java applications.
Panel A generic lightweight container.
Label A display area for a short text string or an image or both.
Radio Button An item that can be selected or deselected.
Combo Box A component that combines a button or editable fields and a drop-down list.

Text Field A lightweight component that allows the editing of a single line text.

Scroll Bar A component that allows to adjust the contents of the viewing area of another
component.
Progress Bar A progress bar typically communicates the progress of some work by displaying its
percentage of completion and possibly a textual display of this percentage.

Password Field A component that allows the editing of a single line of text where the view indicates
something was typed, but does not show the original character.

Table A component used to display and edit regular two-dimensional tables of cells.

Button A “push” button.


Checkbox An item that can be selected or deselected.
List A component that allows user to select one or more objects from a list.

Text Area A multi-line area that displays plain text.


Text Pane A text component that can be marked up with attributes that are represented
graphically.
Let’s start designing our Registration, Login and Home Page.
Do not forget to be descriptive in naming your Variables.
 To start connecting our database.
 Under Projects, locate your created Project, from there right-click on Libraries > Add JAR
Folder
 Locate your downloaded mysql-connector-j-8.3.0
It can now be found under the Libraries folder as mysql-connector-j-8.3.0.jar

In your created Java class enter the following code:


It can now be found under the Libraries folder as mysql-connector-j-8.3.0.jar

In your created Java class enter the following code:


// Creating an instance of the shs_login class named
shs_loginFrame
shs_login shs_loginFrame = new shs_login();

// Setting the visibility of the shs_loginFrame to true, making it


visible on the screen
shs_loginFrame.setVisible(true);

// Packing the components within the shs_loginFrame to fit their


preferred sizes
shs_loginFrame.pack();

// Setting the location of the shs_loginFrame relative to the center


of the screen
shs_loginFrame.setLocationRelativeTo(null);
Let’s start preparing our Login Frame.

 In our Login Frame, we have created two (2) buttons. Login and Register. Let’s code our Register button, so that when we click
it, it’ll proceed in our Register Frame.
 Double click the REGISTER button and enter the following code:
 Do the same thing with the Registration Frame so that both frames are now linked.

CODING THE REGISTER FRAME

 Open XAMPP Control Panel and Start “Apache” and “MySQL”.


 Click the Admin Button of “MySQL” or simply type in your browser http://localhost/phpmyadmin/
It should look like this:
 To create a database, click New.
 Enter your database Name then click Create.
 You’ll be asked to create Table Name and select Number of Columns (this depends on what the
programmer needs)
 For this example, we used accountUsername and accountPassword.
 To create a database, click New.
 Enter your database Name then click Create.
 You’ll be asked to create Table Name and select Number of Columns (this depends on what the programmer needs)
 For this example, we used accountUsername and accountPassword.
 Let’s go back to our Register Frame and start coding our Register Button.
 Double click the Register button to enter your codes, this will take you to the Source View of the Register
Frame.
 Type the following import statements, for later use.
import java.sql.Connection; This import statement is used to import the Connection interface
from the java.sql package. This interface represents a connection
to a database, allowing Java programs to interact with relational
databases.
import java.sql.DriverManager; This import statement is used to import the DriverManager class
from the java.sql package. The DriverManager class is responsible
for managing JDBC drivers, which are required for establishing
connections to different types of databases.
import java.sql.ResultSet; This import statement is used to import the ResultSet interface from
the java.sql package. The ResultSet interface represents the result
set of a database query, allowing Java programs to iterate over the
rows of the result set and retrieve data from the database.

import java.sql.Statement; This import statement is used to import the Statement interface
from the java.sql package. The Statement interface represents a SQL
statement that is sent to the database for execution. It allows Java
programs to execute SQL queries, updates, and other database
operations.
import javax.swing.JFrame; This import statement is used to import the JFrame class from the
javax.swing package. The JFrame class represents a window in a Java
GUI application. It provides the basic functionalities of a window,
such as borders, title bars, and menus.
import javax.swing.JOptionPane; This import statement is used to import the JOptionPane class from
the javax.swing package. The JOptionPane class provides methods
for creating and managing dialog boxes, including message dialogs,
input dialogs, and option dialogs, in Java GUI applications.
Let’s start coding the Register button.
// Method to handle the action when the register button is clicked
private void btnRegRegisterActionPerformed(java.awt.event.ActionEvent evt) {

// Declaration of variables to store username, password, and SQL query


String username, password, query;

// Declaration of variables to store URL, username, and password for database connection
String SUrl, SUser, SPass;

// Setting the URL, username, and password for the database connection
SUrl = "jdbc:MySQL://localhost:3306/shs_db";
SUser = "root";
SPass = "";

try {
// Loading the MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establishing a connection to the database


Connection con = DriverManager.getConnection(SUrl, SUser, SPass);

// Creating a statement object for executing SQL queries


Statement st = con.createStatement();

// Checking if the username field is empty


if ("".equals(txtRegUsername.getText())){

// Displaying an error message if the username field is empty


JOptionPane.showMessageDialog(new JFrame(), "Username is required", "ERROR", JOptionPane.ERROR_MESSAGE);

// Checking if the password field is empty


} else if (txtRegPassword.getPassword().length == 0){

// Displaying an error message if the password field is empty


JOptionPane.showMessageDialog(new JFrame(), "Password is required", "ERROR", JOptionPane.ERROR_MESSAGE);

} else {
// If both fields are filled, retrieving the username and password
username = txtRegUsername.getText();

// Getting the password from the password field


char[] passwordChars = txtRegPassword.getPassword();

// Converting the password characters to a String


password = new String(passwordChars);

// Creating an SQL query to insert the username and password into the database
query = "INSERT INTO accountdetails(accountUsername, accountPassword)"+
"VALUES('"+username+"', '"+password+"')";

// Executing the SQL query


st.execute(query);

// Clearing the username and password fields


txtRegUsername.setText("");
txtRegPassword.setText("");

// Displaying a success message


JOptionPane.showMessageDialog(this, "Account created successfully!");
}

// Catching any exceptions that might occur during database connection or query execution
} catch (Exception e){
JOptionPane.showMessageDialog(this, "Error occurred during registration. Please try again later.");
}
}
What is a try-catch block?
a try-catch block is a mechanism used to handle exceptions, which are unexpected
events that occur during the execution of a program.

CODING THE LOGIN FRAME

Open the Design View of our Login Frame.


Double click on the LOGIN button to enter our code.
Do not forget to import our statements like we did in the
Registration Frame.
Let’s go back and code our Login button, type the
following code:
What is a try-catch block?
a try-catch block is a mechanism used to handle exceptions, which are unexpected
events that occur during the execution of a program.

CODING THE LOGIN FRAME

Open the Design View of our Login Frame.


Double click on the LOGIN button to enter our code.
Do not forget to import our statements like we did in the
Registration Frame.
Let’s go back and code our Login button, type the
following code:
// Declaration of variables
String username, password, query, uname = null, passDb =
null;
String SUrl, SUser, SPass;

// Database connection details


SUrl = "jdbc:MySQL://localhost:3306/shs_db";
SUser = "root";
SPass = "";
int notFound = 0; // Flag to check if user is found in
database
Do not worry it may seem like a lot, but we’ll understand
what these means.
There will be an error once you’re done but we will fix
that!
Do not worry it may seem like a lot, but we’ll understand
what these means.
There will be an error once you’re done but we will fix
that!

You might also like