为什么要使用预编译语句而不是使用go sql包中的Query/Exec方法?

huangapple go评论80阅读模式
英文:

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

问题

在Go的sql包中,我了解到每个语句在执行后都应该关闭。为什么有人会使用预处理语句而不仅仅使用原始的QueryExec方法呢?

英文:

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?

答案1

得分: 3

我认为最好的答案来自维基百科上关于"Prepared Statements"(预编译语句)的文章。

引用:

编译和优化语句的开销只会发生一次,尽管该语句会被执行多次。并非所有的优化都可以在预编译语句时进行,原因有两个:最佳计划可能取决于参数的具体值,而且随着表和索引随时间变化,最佳计划可能会发生变化。

预编译语句对抗SQL注入具有弹性,因为稍后使用不同协议传输的参数值无需正确转义。如果原始语句模板不是来自外部输入,就不会发生SQL注入。

英文:

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.

答案2

得分: 2

准备好的语句已经绑定到具体的数据库连接,包含低级别的driver.Stmt,并且可以被多个go协程并发使用。因此,准备和使用它非常方便,而且速度更快。

英文:

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.

huangapple
  • 本文由 发表于 2015年1月15日 01:03:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/27948469.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定