<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'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't being replaced for some reason and I cannot figure out why. Here's a piece of code where it occurs:</p>
<pre><code>func updateDatabase(user *User, tx *sql.Tx) {
update, err := tx.Prepare("UPDATE locations SET ?=?+? WHERE city=? AND state=? AND country=?")
if err != nil {
log.Println(err)
tx.Rollback()
return
}
defer update.Close()
for k, v := range user.licenses {
if v > 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'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 "don't do that!"</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, "=?,") + "=?" + sqlPartialUpdatePart2
....
values = append(values, city, state, country)
stmt.Exec(values...)
</code></pre></pre>jtsylve: <pre><p>It'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
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传