📅  最后修改于: 2023-12-03 15:39:39.860000             🧑  作者: Mango
在开发过程中,经常需要向数据库中插入新的数据并获得插入数据的 ID。在 Java 中,可以使用 JDBC 连接数据库并执行 SQL 语句来实现该操作。
以下是一个示例程序,该程序演示了如何插入新的房间记录到数据库并返回插入记录的 ID。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
public class RoomInsert {
private static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USER = "username";
private static final String PASS = "password";
public static void main(String[] args) {
String roomName = "Executive Suite";
String roomDescription = "Spacious room with king-size bed, separate living area and ocean view.";
int roomPrice = 200;
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO rooms(name, description, price) VALUES (?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) {
pstmt.setString(1, roomName);
pstmt.setString(2, roomDescription);
pstmt.setInt(3, roomPrice);
int affectedRows = pstmt.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Inserting room record failed, no rows affected.");
}
try (ResultSet generatedKeys = pstmt.getGeneratedKeys()) {
if (generatedKeys.next()) {
int roomId = generatedKeys.getInt(1);
System.out.println("New room record inserted with ID: " + roomId);
} else {
throw new SQLException("Inserting room record failed, no ID obtained.");
}
}
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage());
}
}
}
private static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USER = "username";
private static final String PASS = "password";
在实际使用时,请将 DB_URL
替换为实际的数据库 URL,USER
替换为实际的用户名,PASS
替换为实际的密码。
String roomName = "Executive Suite";
String roomDescription = "Spacious room with king-size bed, separate living area and ocean view.";
int roomPrice = 200;
在实际使用时,请将这些值替换为要插入的实际值。
DriverManager
创建与数据库的连接。try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement
在数据库中插入新的房间记录。PreparedStatement pstmt = conn.prepareStatement("INSERT INTO rooms(name, description, price) VALUES (?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) {
pstmt.setString(1, roomName);
pstmt.setString(2, roomDescription);
pstmt.setInt(3, roomPrice);
int affectedRows = pstmt.executeUpdate();
在 PreparedStatement
中,我们使用 ?
占位符来代替实际的值,然后在 setXXX()
方法中将实际的值设置到占位符中。注意,我们在 PreparedStatement
的构造函数中使用了 Statement.RETURN_GENERATED_KEYS
参数,以便在插入记录后返回插入记录的 ID。
ResultSet
获取插入记录的 ID。try (ResultSet generatedKeys = pstmt.getGeneratedKeys()) {
if (generatedKeys.next()) {
int roomId = generatedKeys.getInt(1);
System.out.println("New room record inserted with ID: " + roomId);
} else {
throw new SQLException("Inserting room record failed, no ID obtained.");
}
}
以上是一个简单的示例程序,演示了如何使用 JDBC 在 Java 中插入新的房间记录并返回插入记录的 ID。注意,在实际使用中,您需要根据自己的需要对代码进行修改和调整。