为什么在 go sql 包中使用准备好的语句而不是 Query / Exec?

Why use prepared statements instead of Query / Exec with go sql package?

在gosql包中,我理解每条语句执行完都要关闭。 为什么有人会使用准备好的语句而不只是原始的 QueryExec 方法?

准备好的语句已经绑定到数据库的具体连接,包含低级 driver.Stmt 并且可以由多个 go-routings 同时使用。所以准备和使用起来非常方便,而且工作速度更快。

我认为最好的答案来自 Prepared Statements 上的维基百科文章。

引用:

The overhead of compiling and optimizing the statement is incurred only once, although the statement is executed multiple times. Not all optimization can be performed at the time the prepared statement is compiled, for two reasons: the best plan may depend on the specific values of the parameters, and the best plan may change as tables and indexes change over time.`enter code here

Prepared statements are resilient against SQL injection, because parameter values, which are transmitted later using a different protocol, need not be correctly escaped. If the original statement template is not derived from external input, SQL injection cannot occur.