How to do SELECT...IN queries via go?

agolangf · · 514 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I keep running into an issue when trying to run a <code>SELECT...IN</code> query on postgres via go. Ideally I would want to run something like:</p> <pre><code>var names = [3]string{&#34;john&#34;,&#34;joe&#34;,&#34;bob&#34;} // or even names := &#34;john,joe,bob&#34; const query = &#34;SELECT * FROM students WHERE name IN ($1)&#34; resp, err := sql.DB.Cursor.Query(query, names) </code></pre> <p>However that doesn&#39;t work because of the way the array gets interpreted in the query. Is there some clean, simple way to achieve this?</p> <p>I&#39;m using lib/pq as my database driver.</p> <hr/>**评论:**<br/><br/>cs-guy: <pre><p>If you don&#39;t mind bringing in another package, github.com/jmoiron/sqlx has a helper for this use case. <a href="https://godoc.org/github.com/jmoiron/sqlx#In" rel="nofollow">https://godoc.org/github.com/jmoiron/sqlx#In</a></p></pre>Blufalcon94: <pre><p>Oh wow, I don&#39;t know how I&#39;ve never seen that! The package in general seems really useful! Thank you</p></pre>Blufalcon94: <pre><p>Is there some way to use that function as more of a utility as opposed to it being my main database package?</p></pre>jasrags: <pre><p>That package just extends the base SQL. You still have access to all of the regular methods.</p></pre>lapingvino: <pre><p>change the $1 for %s, use a Sprintf writing to a new variable to create the $1, $2 etc as much as you need them (use len(names)) and use names... instead of names when you invoke it.</p></pre>Fwippy: <pre><p>Doesn&#39;t that open you up for SQL injection, though?</p></pre>lapingvino: <pre><p>no, because you only generate the numbers, you don&#39;t actually put user input in the string itself.</p></pre>Fwippy: <pre><p>Ohh, gotcha.</p></pre>dominosci: <pre><p>I think you can use back tics.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

514 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传