英文:
Inserting into a Postgresql table with Go
问题
我有以下表格:
CREATE TABLE Users (
user_id BIGSERIAL PRIMARY KEY,
email VARCHAR(50) NOT NULL,
password_hash VARCHAR(100) NOT NULL,
points INT DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)
我接收一个电子邮件和密码,加密密码并尝试将它们插入表格中:
import (
_ "github.com/lib/pq"
"database/sql"
"code.google.com/p/go.crypto/bcrypt"
)
conn := OpenConnection()
defer conn.Close()
email := r.FormValue("email")
password, _ := bcrypt.GenerateFromPassword([]byte(r.FormValue("password")), bcrypt.DefaultCost)
res, err := conn.Exec("INSERT INTO users (email, password_hash) VALUES (?, ?)", email, password)
http.Redirect(w, r, "/", http.StatusFound)
插入操作抛出了 pq:"51" S:"ERROR" L:"1002" C:"42601" M:"syntax error at or near ","" F:"scan.l" R:"scanner_yyerror"
的错误。如果我将字节类型的密码替换为简单的字符串,会抛出相同的错误。
我做错了什么?
英文:
I have the following table:
CREATE TABLE Users (
user_id BIGSERIAL PRIMARY KEY,
email VARCHAR(50) NOT NULL,
password_hash VARCHAR(100) NOT NULL,
points INT DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)
I take in a email and password, encrypt the password and attempt to insert them into the table:
import (
_ "github.com/lib/pq"
"database/sql"
"code.google.com/p/go.crypto/bcrypt"
)
conn := OpenConnection()
defer conn.Close()
email := r.FormValue("email")
password, _ := bcrypt.GenerateFromPassword([]byte(r.FormValue("password")), bcrypt.DefaultCost)
res, err := conn.Exec("INSERT INTO users (email, password_hash) VALUES (?, ?)", email, password)
http.Redirect(w, r, "/", http.StatusFound)
The insert throws pq: P:"51" S:"ERROR" L:"1002" C:"42601" M:"syntax error at or near \",\"" F:"scan.l" R:"scanner_yyerror"
. The same error is thrown if i replace the byte type password with a simple string.
What am I doing wrong?
答案1
得分: 2
我会在链接消失的情况下发布一个答案:
来自https://github.com/lib/pq/issues/65
> 由dpapathanasiou提供:
> 我已经找到了问题所在;这不是pq的bug,而是我创建准备语句的方式有问题:我需要使用($n)而不是?来绑定参数。
>
> 所以这些语句都可以正确工作:
stmt, err := db.Prepare("select id from people where firstname = ($1) and lastname = ($2)")
stmt, err := db.Prepare("select id from people where firstname ~* ($1) and lastname ~* ($2)")
stmt, err := db.Prepare("select id from people where firstname = ($1)")
英文:
I will post as an answer in case the link goes away:
From https://github.com/lib/pq/issues/65
> by dpapathanasiou :
> I've figured out the problem; it's not a bug in pq but in the way I
> was creating the prepared statements: I need to use ($n) instead of ?
> for the bound parameters.
>
> So all of these statements work correctly:
stmt, err := db.Prepare("select id from people where firstname = ($1) and lastname = ($2)")
stmt, err := db.Prepare("select id from people where firstname ~* ($1) and lastname ~* ($2)")
stmt, err := db.Prepare("select id from people where firstname = ($1)")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论