Day 1: Introduction to Java

icon picker
Day 15: JDBC - Database Connectivity

Java Database Connectivity (JDBC): A Comprehensive Guide

Introduction to JDBC

JDBC is a Java-based API that allows Java applications to interact with relational databases like MySQL, Oracle, PostgreSQL, and more. It provides a standard interface for connecting to databases, executing SQL queries, and handling query results.
Let's begin by importing the necessary Java packages for JDBC:
javaCopy code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

Connecting to a Database

To connect to a database, you need to establish a connection using the Connection object. Here's how you can do it:
javaCopy code
public static Connection getConnection() throws SQLException {
String jdbcUrl = "jdbc:mysql://localhost:3306/mydatabase";
String username = "your_username";
String password = "your_password";
Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
return connection;
}

Replace "jdbc:mysql://localhost:3306/mydatabase", "your_username", and "your_password" with your database URL, username, and password.

Executing SQL Queries

Once you have a connection, you can execute SQL queries. For instance, let's select all records from a table:
javaCopy code
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public static void main(String[] args) {
try {
Connection connection = getConnection();
Statement statement = connection.createStatement();
String sql = "SELECT * FROM mytable";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
// Process each row of the result set here
}
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

Handling ResultSets

The ResultSet object contains the query result. You can iterate through it to retrieve data:
javaCopy code
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
// Process data
}

Complete Login and Registration with database
package JavaCompleteCourse;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class day15 {
private static final String DB_URL = "jdbc:mysql://your_database_url:your_port/your_database_name";
private static final String DB_USER = "your_database_username";
private static final String DB_PASSWORD = "your_database_password";

private JFrame frame;
private JTextField usernameField;
private JPasswordField passwordField;
private JPanel loginPanel;
private JPanel welcomePanel;

public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
try {
new day15();
} catch (Exception e) {
e.printStackTrace();
}
});
}

public day15() {
frame = new JFrame("Login Example");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);

loginPanel = createLoginPanel();
welcomePanel = createWelcomePanel();

frame.setContentPane(loginPanel);

frame.setVisible(true);
}

private JPanel createLoginPanel() {
JPanel panel = new JPanel();
panel.setLayout(null);

JLabel usernameLabel = new JLabel("Username:");
usernameLabel.setBounds(50, 50, 80, 25);
panel.add(usernameLabel);

JLabel passwordLabel = new JLabel("Password:");
passwordLabel.setBounds(50, 80, 80, 25);
panel.add(passwordLabel);

usernameField = new JTextField();
usernameField.setBounds(150, 50, 150, 25);
panel.add(usernameField);

passwordField = new JPasswordField();
passwordField.setBounds(150, 80, 150, 25);
panel.add(passwordField);

JButton loginButton = new JButton("Login");
loginButton.setBounds(50, 120, 100, 25);
panel.add(loginButton);

JButton registerButton = new JButton("Register");
registerButton.setBounds(200, 120, 100, 25);
panel.add(registerButton);

loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
char[] passwordChars = passwordField.getPassword();
String password = new String(passwordChars);

if (login(username, password)) {
frame.setContentPane(welcomePanel);
frame.revalidate();
} else {
JOptionPane.showMessageDialog(frame, "Invalid username or password.");
}
}
});

registerButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
char[] passwordChars = passwordField.getPassword();
String password = new String(passwordChars);

if (register(username, password)) {
JOptionPane.showMessageDialog(frame, "Registration successful!");
} else {
JOptionPane.showMessageDialog(frame, "Registration failed.");
}
}
});

return panel;
}

private JPanel createWelcomePanel() {
JPanel panel = new JPanel();
panel.setLayout(null);

JLabel welcomeLabel = new JLabel("Welcome!");
welcomeLabel.setBounds(150, 50, 100, 25);
panel.add(welcomeLabel);

JButton logoutButton = new JButton("Logout");
logoutButton.setBounds(150, 100, 100, 25);
panel.add(logoutButton);

logoutButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.setContentPane(loginPanel);
frame.revalidate();
usernameField.setText("");
passwordField.setText("");
}
});

return panel;
}

private boolean login(String username, String password) {
try {
Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
String query = "SELECT * FROM users WHERE username=? AND password=?";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
ResultSet resultSet = preparedStatement.executeQuery();
return resultSet.next();
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

private boolean register(String username, String password) {
try {
Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
String query = "INSERT INTO users (username, password) VALUES (?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
int result = preparedStatement.executeUpdate();
return result > 0;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}


Database
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(255) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL
);

Exercise Questions

What is JDBC, and why is it important for Java developers?
Explain the steps involved in connecting to a database using JDBC.
Write a Java code snippet to insert a new record into a database table.
How do you handle exceptions when working with JDBC?
What is a ResultSet, and how do you retrieve data from it?

Answers

JDBC stands for Java Database Connectivity, and it's important for Java developers because it provides a standardized way to connect Java applications with relational databases, allowing them to perform operations like querying, updating, and managing data.
The steps to connect to a database using JDBC are importing necessary packages, loading the database driver, establishing a connection, creating a statement, executing SQL queries, and handling the results.
To insert a new record into a database table, you can use an SQL INSERT statement within a Java JDBC code block. You need to create a Connection object, create a Statement object, and then execute the INSERT statement.
Exception handling is crucial in JDBC since it involves interactions with databases, which may lead to exceptions. Common exceptions include SQLException, ClassNotFoundException, and IOException. Proper error handling ensures the graceful recovery from these issues.
A ResultSet is an object that represents the result set of an executed SQL query. You can use methods like next(), getInt(), getString(), and others to retrieve data from it row by row.
This concludes our overview of JDBC, a fundamental technology for Java developers to interact with databases. JDBC empowers you to perform database operations efficiently and effectively, making it an indispensable skill for any Java programmer.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.