Connection, Statement, and ResultSet hold database sessions, cursors, and driver memory, so they must close in reverse order of creation: ResultSet, Statement, then Connection. Always use try-with-resources so every resource closes reliably even on exceptions, rather than fragile nested finally blocks. With a connection pool, calling Connection.close does not drop the TCP socket—it returns the connection to the pool for reuse. Failing to close it causes leaks that exhaust the pool and leave open transactions holding locks, so we use JdbcTemplate or JPA plus HikariCP leakDetectionThreshold in production.
Key terms:try-with-resources, connection leak, pool return, leakDetectionThreshold
Likely follow-up: "What happens to an uncommitted transaction if a Connection is returned to a connection pool without an explicit rollback?"
PreparedStatement 把 SQL 结构和参数值彻底分离:先用带问号占位符的模板固定语句结构,再通过 set 方法绑定参数——服务端预编译时通过协议单独传参,像 MySQL 驱动默认的客户端预编译则由驱动按类型严格转义后填入。无论哪种,绑定的值都只会被当成纯字面量数据,改变不了语法结构,从根本上防住注入。除此之外,它还能在服务端预编译时复用执行计划,并自动处理日期和引号转义,所以默认都应该用 PreparedStatement。
但有两个常见盲区必须强调:第一,问号占位符只能代替值,不能代替表名、列名、ORDER BY 排序字段和升降序,这些动态结构必须在代码里用严格白名单映射;第二,如果先把用户输入拼成 SQL 再传给 prepareStatement,跟用 Statement 毫无区别,照样会被注入。
English PitchEnglish · ~55s
Statement executes a raw SQL string directly, so concatenating user input lets attackers inject SQL syntax and alter query structure. PreparedStatement separates structure from data: the parameterized template locks in the SQL structure, and values bound via setters are either sent separately via server-side preparation or safely type-escaped by the driver—as MySQL Connector/J does by default—so inputs are always treated strictly as literal data, neutralizing SQL injection while enabling execution plan reuse when server-side prepared. The key caveat is that placeholders only represent values—never table names, columns, or ORDER BY directions—so dynamic identifiers require a strict allowlist, and concatenating input before calling prepareStatement defeats the protection completely.
Key terms:PreparedStatement, parameter binding, SQL injection, execution plan reuse, allowlist
Likely follow-up: "How do you safely handle dynamic ORDER BY columns or variable-length IN clauses when using PreparedStatement?"
批量插入时取主键的限制:是否支持、返回的顺序是否和插入顺序一致,取决于数据库和驱动。MySQL 在开启批量改写后,是根据第一条的 ID 和行数推算出一段连续的值,这依赖自增锁的模式(innodb_autoinc_lock_mode),INSERT ... ON DUPLICATE KEY UPDATE 这类语句推算可能不准。需要可靠的 ID 时,在应用层预先生成(雪花算法、UUID、数据库序列批量取号)。
In JDBC, a transaction is scoped to a single Connection, and new connections default to autoCommit=true, meaning every statement commits immediately as its own transaction. To group multiple statements atomically—like debiting one account and crediting another—you call setAutoCommit(false) and finish explicitly with commit or rollback. Always roll back in the catch path, otherwise uncommitted changes and row locks linger on the connection and can poison the next pool borrower. You can also set isolation levels per connection and use Savepoints for partial rollbacks, which is how Spring implements nested transactions.
Likely follow-up: "Why does Spring default to rolling back only on unchecked exceptions, and how does it bind a JDBC Connection to the current thread?"
这就解释了两个高频坑:在事务里另开子线程查库不在同一事务里,因为新线程读不到原线程的 ThreadLocal;自己直接调 DataSource.getConnection 绕过了 Spring 绑定,拿到的也是新连接,同样不参与事务。
English PitchEnglish · ~65s
A database transaction belongs to a single connection session: another connection cannot see its uncommitted writes at standard isolation levels or commit and roll back atomically with it. If two DAOs borrow separate pooled connections, one can commit before the other fails. Rather than passing a Connection through every method signature, Spring binds it to the current thread. On entering a @Transactional method, DataSourceTransactionManager borrows one connection, disables autoCommit, and stores it in TransactionSynchronizationManager's ThreadLocal keyed by DataSource. JdbcTemplate and MyBatis resolve the bound connection via DataSourceUtils—while JPA binds its EntityManager via JpaTransactionManager using the same ThreadLocal mechanism—so all DAOs share one transaction until commit or rollback, which is also why child threads or direct dataSource.getConnection() calls fall outside the transaction.
Likely follow-up: "Why can Propagation.REQUIRES_NEW deadlock a small connection pool under high concurrency, and how does reactive Spring propagate transactions without ThreadLocal?"
建立一条数据库连接要经过 TCP 握手、认证和会话初始化,代价很高。连接池预先建好一批连接反复使用,省掉这个开销,同时限制了应用对数据库的最大并发数,保护数据库。连接数不是越多越好:数据库能并行处理的请求受 CPU 核数和磁盘限制,连接再多也只是在数据库里排队和争抢,加上每条连接占用内存和上下文切换,吞吐反而下降。池应该小一些,让请求在应用这一侧排队。还要算上实例数,总连接数不能超过数据库的上限。
正式解释
连接池做的事:
作用
说明
复用连接
借用和归还是微秒级,新建连接是毫秒到几十毫秒
限制并发
maximumPoolSize 是应用对数据库并发数的硬上限,突发流量不会把数据库打垮
管理连接的健康
检测并替换失效的连接,定期淘汰老连接
排队与超时
没有空闲连接时让线程等待,超时则快速失败
监控
活跃数、空闲数、等待线程数、取连接的耗时
为什么小池子更快:数据库同一时刻能真正执行的查询数量大约等于 CPU 核数(加上等待 I/O 的那部分)。连接数远超这个数时,多出来的查询并没有被更快地处理,而是在数据库内部争抢 CPU、锁和缓存,上下文切换增多,每个查询都变慢。把并发限制在数据库处理得过来的水平,其余请求在应用的连接池前排队,总吞吐更高、延迟更稳定。
Opening a database connection requires a TCP handshake, authentication, and session setup, so a connection pool pre-creates and reuses connections while capping concurrency to protect the database. Larger pools actually hurt throughput because a database can only run roughly as many parallel queries as its CPU cores and disk I/O allow. Adding hundreds of connections just shifts queuing into the database, spiking lock contention and context switching; keeping the pool small lets excess traffic queue cheaply in the app. Always multiply per-instance pool size by max pod count—including rolling deploys—so you stay under the database limit.
Key terms:connection pool sizing, HikariCP, contention, maxLifetime, total connection budget
Likely follow-up: "Why should HikariCP maxLifetime be configured shorter than the database or NAT gateway idle timeout?"
现象是取连接超时,报 Connection is not available。先看连接池的指标:活跃连接是否等于上限、有多少线程在等。再分两种情况。一种是连接借出去不还或被长时间占用:事务里调用了很慢的外部接口、有慢 SQL、在等锁。抓线程转储看持有连接的线程在做什么,开启泄漏检测看连接在哪里借出。另一种是并发量超过了池的容量。不要先调大连接池,先缩短占用连接的时间。
正式解释
典型的报错:
示意
SQLTransientConnectionException: HikariPool-1 - Connection is not available,
request timed out after 30000ms (total=10, active=10, idle=0, waiting=37)
connectionTimeout 调短(如 2–5 秒),池耗尽时快速失败,不要让 Web 线程也跟着被占满。
给查询和事务设置超时。
事务里不做远程调用。
关闭 Spring 的 spring.jpa.open-in-view:它让连接在整个 HTTP 请求期间(包括渲染响应)都被占着。
监控并对 pending > 0 持续一段时间、timeout 次数告警。
在测试里复现这些行为:用 Testcontainers 启动真实的 MySQL 或 PostgreSQL,而不是 H2,因为锁、隔离级别、超时、驱动的行为各数据库不同。可以把池设得很小(如 2 条),并发执行来验证:连接是否归还、事务是否回滚、超时是否生效、数据库重启后池能否恢复。
面试口语版中文 · 约 110 秒
连接池耗尽的典型报错是 Connection is not available, request timed out。排查我分两步:先看 HikariCP 指标(活跃连接数是否顶满、等待队列有多少线程),再同时抓应用线程转储和数据库活跃会话,看占着连接的会话是在跑慢 SQL、等行锁,还是 idle in transaction 空挂着。
When a pool is exhausted, threads wait for a connection until they fail with a timeout. I first check pool metrics—active versus max connections and pending waiters—then grab a thread dump alongside database active sessions to see whether connections are running slow SQL, waiting on locks, or sitting idle in an open transaction. The top production culprit is making slow remote HTTP calls inside a transaction, followed by leaks, slow SQL, or nested REQUIRES_NEW self-deadlocks. Never blindly raise the pool size first—that only masks leaks or crushes the database; shorten hold time and enable leak detection and tight timeouts instead.
List<User> users = jdbcTemplate.query(
"SELECT id, name FROM users WHERE status = ?",
(rs, rowNum) -> newUser(rs.getLong("id"), rs.getString("name")),
status);
intn= jdbcTemplate.update("UPDATE users SET name = ? WHERE id = ?", name, id);