<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{"john","joe","bob"} // or even names := "john,joe,bob"
const query = "SELECT * FROM students WHERE name IN ($1)"
resp, err := sql.DB.Cursor.Query(query, names)
</code></pre>
<p>However that doesn'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'm using lib/pq as my database driver.</p>
<hr/>**评论:**<br/><br/>cs-guy: <pre><p>If you don'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't know how I'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't that open you up for SQL injection, though?</p></pre>lapingvino: <pre><p>no, because you only generate the numbers, you don'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
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传