MySQL 如何使用Java将数据插入MySQL数据库?

MySQL 如何使用Java将数据插入MySQL数据库?

MySQL是最流行的关系型数据库之一,Java则是最受欢迎的编程语言之一。 在Java中操作数据库是非常常见的需求,下面将展示如何使用Java将数据插入MySQL数据库。在这个例子中,我们将使用JDBC驱动程序连接到MySQL服务器并插入数据。

要连接到MySQL服务器,首先需要下载MySQL JDBC驱动程序。 下载地址:https://dev.mysql.com/downloads/connector/j/

下载后,将JDBC驱动程序添加到项目中。
我们将使用以下步骤将数据插入MySQL数据库。

阅读更多:MySQL 教程

步骤:

  1. 导入MySQL JDBC驱动程序。 以下是一个典型的导入语句
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
  1. 访问MySQL服务器。创建一个名为connection的静态变量,并使用以下代码访问数据库
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/DATABASE_NAME";
String username="root";
String password="password";
Connection conn = DriverManager.getConnection(url, username, password);

以下是上述代码的解释:

  • Class.forName() — 返回与给定字符串名的类或接口相关联的 Class 对象。
  • com.mysql.jdbc.Driver — MySQL提供的JDBC驱动程序。
  • jdbc:mysql://localhost:3306/DATABASE_NAME — 数据库连接的URL。
  • “root” 和 “password” — MySQL用户的用户名和密码。
  1. 创建sql语句,用于向MySQL数据库插入数据。以下是示例代码
String sql = "INSERT INTO tablename (column1, column2, column3,...) VALUES (?, ?, ?, ...)";
  1. 根据我们创建的 sql 语句,创建 PreparedStatement 对象,该对象执行 SQL 准备语句。
PreparedStatement statement = conn.prepareStatement(sql);
  1. 为参数设置值,用于将数据插入到预处理语句中。以下是示例代码:
statement.setString(1, "John Doe");
statement.setString(2, "john@example.com");
statement.setInt(3, 25);
  1. 执行PreparedStatement对象,将数据插入MySQL数据库中。
statement.executeUpdate();
  1. 关闭PreparedStatement和数据库连接。
statement.close();
conn.close();

完整代码如下:

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

public class InsertDataToMySQL {
    public static void main(String[] args) {
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url="jdbc:mysql://localhost:3306/DATABASE_NAME";
            String username="root";
            String password="password";
            conn = DriverManager.getConnection(url, username, password);

            String sql = "INSERT INTO tablename (column1, column2, column3,...) VALUES (?, ?, ?, ...)";
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1, "John Doe");
            statement.setString(2, "john@example.com");
            statement.setInt(3, 25);
            statement.executeUpdate();
            statement.close();
            conn.close();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
}

结论

就这样,我们展示了如何使用Java将数据插入MySQL数据库。 通过连接到数据库,创建预处理语句并执行,您可以轻松地将数据插入数据库。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程