[Java Advanced] Detailed explanation of JDBC login case

Insert image description here

In this article, we will use a simple JDBC login case to introduce in detail how to use Java Database Connection (JDBC) to connect to the database, perform user authentication and other operations. This case will be suitable for database beginners, we will build a simple login system from scratch.

What is JDBC?

JDBC is the abbreviation of Java Database Connectivity. It is part of the Java standard library and is used to communicate with databases. Through JDBC, Java applications can connect to various relational databases, such as MySQL, Oracle, SQL Server, etc., and perform database operations such as querying, inserting, updating, and deleting data.

Preparation

Before you begin, make sure you have completed the following preparations:

  1. Install and configure the Java development environment.
  2. Download and install a database management system such as MySQL. Make sure you remember the database server's hostname, port, username, and password.

Create database

First, we need to create a database to store user information. In MySQL, you can create a database named "userdb" using the following SQL command:

CREATE DATABASE userdb;

Next, we create a table named "users" to store user information. The table will contain the following columns:

  • id: The user’s unique identifier (primary key)
  • username:username
  • password:password

The following is the SQL command to create the "users" table:

USE userdb;

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

Write Java programs

Now, we will create a Java program to connect to the database via JDBC and authenticate the user.

Import necessary libraries

First, import the libraries for JDBC in Java:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

Connect to database

In Java, to connect to a database we need to provide the URL of the database, username and password. This information will be used to establish a connection to the database. Here is a sample code to connect to a MySQL database:

public class JDBCLoginExample {
    
    
    // 数据库 URL,注意将 <hostname>、<port>、<database>、<username> 和 <password> 替换为实际值
    private static final String DB_URL = "jdbc:mysql://<hostname>:<port>/<database>";
    private static final String USER = "<username>";
    private static final String PASSWORD = "<password>";

    public static void main(String[] args) {
    
    
        try {
    
    
            // 注册 JDBC 驱动程序
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 建立数据库连接
            Connection connection = DriverManager.getConnection(DB_URL, USER, PASSWORD);

            // TODO: 在这里执行后续操作

            // 关闭数据库连接
            connection.close();
        } catch (SQLException | ClassNotFoundException e) {
    
    
            e.printStackTrace();
        }
    }
}

In the above code, we use Class.forName()the method to load the MySQL JDBC driver and DriverManager.getConnection()establish a connection with the database through the method. Be sure to replace <hostname>, <port>, <database>, <username>and <password>with your actual database information.

User authentication

Next, we'll write code to authenticate the user. The user will provide a username and password and we will check if a matching record exists in the database.

// 用户输入的用户名和密码
String inputUsername = "user1";
String inputPassword = "password123";

// SQL 查询语句
String query = "SELECT * FROM users WHERE username = ? AND password = ?";
try {
    
    
    // 创建 PreparedStatement 对象
    PreparedStatement preparedStatement = connection.prepareStatement(query);
    
    // 设置查询参数
    preparedStatement.setString(1, inputUsername);
    preparedStatement.setString(2, inputPassword);
    
    // 执行查询
    ResultSet resultSet = preparedStatement.executeQuery();
    
    // 检查是否存在匹配的用户
    if (resultSet.next()) {
    
    
        System.out.println("登录成功!");
    } else {
    
    
        System.out.println("用户名或密码不正确。");
    }
    
    // 关闭资源
    resultSet.close();
    preparedStatement.close();
} catch (SQLException e) {
    
    
    e.printStackTrace();
}

Complete Java program

Here is a complete Java program that includes connecting to the database, authenticating the user, and closing the database connection:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCLoginExample {
    
    
    // 数据库 URL,注意将 <hostname>、<port>、<database>、<username> 和 <password> 替换为实际值
    private static final String DB_URL = "jdbc:mysql://<hostname>:<port>/<database>";
    private static final String USER = "<username>";
    private static final String PASSWORD = "<password>";

    public static void main(String[] args) {
    
    
        try {
    
    
            // 注册 JDBC 驱动程序
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 建立数据库连接
            Connection connection = DriverManager.getConnection(DB_URL, USER, PASSWORD);

            // 用户输入的用户名和密码
            String inputUsername = "user1";
            String inputPassword = "password123";

            // SQL 查询语句
            String query = "SELECT * FROM users WHERE username = ? AND password = ?";
            try {
    
    
                // 创建 PreparedStatement 对象
                PreparedStatement preparedStatement = connection.prepareStatement(query);

                // 设置查询参数
                preparedStatement.setString(1, inputUsername);
                preparedStatement.setString(2, inputPassword);

                // 执行查询
                ResultSet resultSet = preparedStatement.executeQuery();

                // 检查是否存在匹配的用户
                if (resultSet.next()) {
    
    
                    System.out.println("登录成功!");
                } else {
    
    
                    System.out.println("用户名或密码不正确。");
                }

                // 关闭资源
                resultSet.close();
                preparedStatement.close();
            } catch (SQLException e) {
    
    
                e.printStackTrace();
            }

            // 关闭数据库连接
            connection.close();
        } catch (SQLException | ClassNotFoundException e) {
    
    
            e.printStackTrace();
        }
    }
}

Be sure to replace <hostname>, <port>, <database>, <username>and <password>with your actual database information. This program compares the username and password entered by the user with the records in the database and outputs an appropriate message based on the results.

This example demonstrates how to use JDBC to connect to a database, create a PreparedStatement object, perform query operations, and close resources. You can extend this program according to actual needs, such as adding user registration functions, error handling, etc. I hope this example helps you understand JDBC and database connections.

Author information

Author: Fanyi
CSDN: https://techfanyi.blog.csdn.net
Nuggets: https://juejin.cn/user/4154386571867191

Guess you like

Origin blog.csdn.net/qq_21484461/article/details/133563198