<p>I had a question about the usage of fmt.Sprintf with SQL statements. I know that this is generally bad and that bindvars and prepared statements should be used for the builtin injection guards, but let's say that I have:</p>
<p>fmt.Sprintf("select * from sometable where id=%d" , someID)</p>
<p>Is there anything that could go wrong or be abused here? Being that we're working with integers, I can't really see what could happen.</p>
<hr/>**评论:**<br/><br/>shazow: <pre><pre><code>fmt.Sprintf("select * from sometable where id=%d" , someID)
</code></pre>
<p>There might not be much that could go wrong with this particular line of code, but the problem is that it's a bad habit. Another developer might pick up the project, or even you yourself in a few months, and try to keep style consistent with an addition:</p>
<pre><code>fmt.Sprintf("select * from sometable where name=%s" , someName)
</code></pre>
<p>And you have yourself an SQL injection. This is how most vulnerabilities happen. The first bad code you write might be just fine, but over time it creates habits that infect all consequent additions and things get more and more broken over time.</p>
<p>It's a good idea to build good habits early and often. :) Never know when it will save you in the future.</p></pre>dgryski: <pre><p>This particular instance is probably safe, but it's <em>very</em> easy to get wrong. It's just cleaner to <em>always</em> use prepared statements so that when requirements change, you don't tweak your Sprintf() to include a string var.</p></pre>FourSigma: <pre><p>Highly recommend this library
if you need some flexibility in your SQL statements.</p>
<p><a href="https://github.com/Masterminds/squirrel" rel="nofollow">https://github.com/Masterminds/squirrel</a></p></pre>ChrisAtWork_HARD: <pre><p>i would make sure that someID can never come directly from user input.</p></pre>weberc2: <pre><p>As long as <code>someID</code> is an int type, you should be okay AFAICT.</p></pre>mortonpe: <pre><p>Echoing the others who have replied you probably should avoid sprintf as it is vulnerable to SQL injection attacks. The safest thing to do would be to use prepared statements <a href="http://go-database-sql.org/retrieving.html" rel="nofollow">http://go-database-sql.org/retrieving.html</a> <- see the first example on this page using the Query function.</p></pre>