go-sql does not replace placeholders in my SQL statements

blov · · 509 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hello,</p> <p>I am using <code>go-sql</code> with the <code>go-sql-driver/mysql</code> driver following <a href="http://go-database-sql.org/index.html" rel="nofollow">go-database-sql&#39;s tutorial</a> to update a MariaDB database. From the <code>mysql</code> driver README and <a href="https://mariadb.com/resources/blog/using-go-mariadb" rel="nofollow">this</a> blog I assume that this should work.</p> <p>However, my <code>?</code> placeholders aren&#39;t being replaced for some reason and I cannot figure out why. Here&#39;s a piece of code where it occurs:</p> <pre><code>func updateDatabase(user *User, tx *sql.Tx) { update, err := tx.Prepare(&#34;UPDATE locations SET ?=?+? WHERE city=? AND state=? AND country=?&#34;) if err != nil { log.Println(err) tx.Rollback() return } defer update.Close() for k, v := range user.licenses { if v &gt; 0 { _, err := update.Exec(k, k, v, user.city, user.state, user.country) if err != nil { log.Println(err) tx.Rollback() return } } } tx.Commit() } </code></pre> <p>Can someone help me?</p> <hr/>**评论:**<br/><br/>YEPHENAS: <pre><p>You can&#39;t use placeholders as column names in prepared statements. Placeholders are for values.</p></pre>fallenunia: <pre><p>That explains a lot. What is the best way to have variable columns? <code>fmt.Sprintf</code>? There is no user generated input since it is a quick script of sorts.</p></pre>yRZ6UqzkuYJhKrf4HY3K: <pre><p>Build the query string dynamically which is usually not recommended for security reasons but if there is no user input, it is probably okay. Also, you could just SET all the possible columns even though only some will have changed.</p></pre>tmornini: <pre><p>Which is a polite way of saying &#34;don&#39;t do that!&#34;</p></pre>riking27: <pre><p>Yeah you basically need to go through a hardcoded list, check if any of them changed, and append to multiple slices.</p> <pre><code>for .... { .... columns = append(columns, colName) // colName MUST come from a string constant values = append(columns, newValue) } if len(columns) == 0 { return } query = sqlPartialUpdatePart1 + strings.Join(columns, &#34;=?,&#34;) + &#34;=?&#34; + sqlPartialUpdatePart2 .... values = append(values, city, state, country) stmt.Exec(values...) </code></pre></pre>jtsylve: <pre><p>It&#39;s sort of annoying, but some drivers use different placeholders than ?. I know at least one of the postgres drivers uses $1, $2, $3, etc. Perhaps this is the case here?</p></pre>

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

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