How to store data in a database using Java?
In order to store data in a database, you need to use Java Database Connectivity (JDBC) to connect to the database and execute corresponding SQL statements. Below is a simple example code that can store data in a MySQL database.
import java.sql.Connection;import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase"; // 数据库连接URL
String username = "root"; // 数据库用户名
String password = "password"; // 数据库密码
try (Connection conn = DriverManager.getConnection(url, username, password)) {
String sql = "INSERT INTO mytable (column1, column2) VALUES (?, ?)"; // SQL插入语句
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, "value1"); // 设置第一个参数的值
statement.setString(2, "value2"); // 设置第二个参数的值
int rowsInserted = statement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("数据插入成功!");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
In this example, we utilized a MySQL database and connected to it via JDBC. We executed an SQL insert statement on a PreparedStatement object and set the parameter values. Finally, we inserted the data into the database by calling the executeUpdate() method.