import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class RDSexample {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://rds_endpoint:3306/test", "username", "password");
conn.setAutoCommit(false);
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE id = ?");
stmt.setInt(1, 1);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}
rs.close();
stmt.close();
conn.commit();
conn.close();
}
}
其中,关键在于设置conn.setAutoCommit(false)
,并在fetch完结果后,手动提交(commit)。这样可以确保查询结果被正确返回。