Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

go

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?

like image 529
Robert Zaremba Avatar asked Oct 28 '25 08:10

Robert Zaremba


1 Answers

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.

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.

like image 121
fabrizioM Avatar answered Oct 29 '25 23:10

fabrizioM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!