In the go sql
package, I understand that each statement should be closed after execution. Why would someone use prepared statements instead of just the raw Query
or Exec
methods?
Prepared statement already bound to concrete connection to DB, contains low-level driver.Stmt and can be used concurrently by multiple go-routings. So it's quite handy to prepare and use, and things work faster.
I think the best answer comes from the wikipedia article on Prepared Statements.
Quoting:
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.