通过PreparedStatement实现对数据库的插入和查询操作。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class PreparedStatementExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String password = "mypassword";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
// 插入数据
String insertSql = "INSERT INTO users (name, age) VALUES (?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(insertSql)) {
pstmt.setString(1, "Jane Doe");
pstmt.setInt(2, 25);
pstmt.executeUpdate();
System.out.println("Data inserted successfully!");
}
// 查询数据
String selectSql = "SELECT * FROM users WHERE name = ?";
try (PreparedStatement pstmt = conn.prepareStatement(selectSql)) {
pstmt.setString(1, "Jane Doe");
try (ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
System.out.println("ID: " + rs.getInt("id") +
", Name: " + rs.getString("name") +
", Age: " + rs.getInt("age"));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}