SoFunction
Updated on 2025-03-03

Java connects to MySQL database and implements data interaction functions

1. Environmental preparation

1.1 Install MySQL

First, make sure you have the MySQL database installed. You can download and install a version suitable for your operating system through the MySQL official website.

1.2 Create databases and tables

After the installation is complete, log in to the MySQL command line tool, create a database named test_db, and create a table named users in it:

CREATE DATABASE test_db;

USE test_db;

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

1.3 Add MySQL Connector/J Dependencies

In a Java project, you need to add MySQL Connector/J as a dependency. If you use Maven, you canAdd the following dependencies to:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.32</version> <!-- Please update according to the latest version -->
</dependency>

2. Java code implementation

2.1 Create a database connection

Next, implement the connection to the MySQL database in Java code. Here is a simple connection example:

package ;

import ;
import ;
import ;

public class MySQLConnection {

    private static final String URL = "jdbc:mysql://localhost:3306/test_db"; // Database address    private static final String USER = "root"; // Database username    private static final String PASSWORD = "your_password"; // Database Password
    public static Connection getConnection() {
        Connection connection = null;
        try {
            // Load the JDBC driver            ("");
            // Get the database connection            connection = (URL, USER, PASSWORD);
            ("The database connection is successful!");
        } catch (ClassNotFoundException e) {
            ("The JDBC driver cannot be found!" + ());
        } catch (SQLException e) {
            ("Database connection failed!" + ());
        }
        return connection;
    }
}

2.2 Insert data

Next, we write a method to insert user data intousersIn the table:

import ;
import ;
import ;

public class UserDAO {

    public void addUser(String username, String password) {
        String sql = "INSERT INTO users (username, password) VALUES (?, ?)";
        
        try (Connection connection = ();
             PreparedStatement preparedStatement = (sql)) {
            (1, username);
            (2, password);
            int rowsAffected = ();
            ("Successfully Inserted" + rowsAffected + "Line data.");
        } catch (SQLException e) {
            ("Insert data failed!" + ());
        }
    }
}

2.3 Query data

Here is a method to query user data:

import ;
import ;
import ;
import ;

public class UserDAO {

    // Other codes...
    public void getAllUsers() {
        String sql = "SELECT * FROM users";
        
        try (Connection connection = ();
             PreparedStatement preparedStatement = (sql);
             ResultSet resultSet = ()) {
             
            while (()) {
                int id = ("id");
                String username = ("username");
                String password = ("password");
                ("User ID: " + id + ", username: " + username + ", password: " + password);
            }
        } catch (SQLException e) {
            ("Query data failed!" + ());
        }
    }
}

2.4 Update data

The method to update user information is as follows:

public class UserDAO {

    // Other codes...
    public void updateUserPassword(int id, String newPassword) {
        String sql = "UPDATE users SET password = ? WHERE id = ?";
        
        try (Connection connection = ();
             PreparedStatement preparedStatement = (sql)) {
             
            (1, newPassword);
            (2, id);
            int rowsAffected = ();
            ("Successfully updated" + rowsAffected + "Line data.");
        } catch (SQLException e) {
            ("Update data failed!" + ());
        }
    }
}

2.5 Delete data

The method of deleting user data is as follows:

public class UserDAO {

    // Other codes...
    public void deleteUser(int id) {
        String sql = "DELETE FROM users WHERE id = ?";
        
        try (Connection connection = ();
             PreparedStatement preparedStatement = (sql)) {
             
            (1, id);
            int rowsAffected = ();
            ("Successfully deleted" + rowsAffected + "Line data.");
        } catch (SQLException e) {
            ("Delete data failed!" + ());
        }
    }
}

3. Test code

Test the above functions in the main program and createMainClass and add the following code:

public class Main {
    public static void main(String[] args) {
        UserDAO userDAO = new UserDAO();

        // Insert the user        ("john_doe", "password123");
        
        // Query the user        ();
        
        // Update user password        (1, "new_password");
        
        // Query the user        ();
        
        // Delete the user        (1);
        
        // Query the user        ();
    }
}

4. Summary

Through this article, you have learned how to connect to MySQL databases and implement data interaction in Java. The main contents include:

  • Database connection: Use JDBC to connect to the MySQL database.
  • Data operation: Implement insert, query, update and delete (CRUD) operations.
  • Best Practices: Use PreparedStatement to avoid SQL injection.

In practical applications, it is recommended to use connection pools such as HikariCP or DBCP to improve performance and resource utilization. At the same time, you can consider using ORM frameworks (such as Hibernate or MyBatis) to simplify database operations and improve development efficiency. I hope this article can help you quickly get started with Java and MySQL data interaction!

The above is the detailed content of Java connecting to MySQL database and implementing data interaction functions. For more information about Java connecting to MySQL data interaction, please pay attention to my other related articles!