使用Go插入Postgresql表

时间:2013-04-28 22:11:39

标签: sql postgresql 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: P:"51" S:"ERROR" L:"1002" C:"42601" M:"syntax error at or near \",\"" F:"scan.l" R:"scanner_yyerror"。如果我用简单的字符串替换字节类型密码,则抛出相同的错误。

我做错了什么?

1 个答案:

答案 0 :(得分:2)

如果链接消失,我会发布答案: 来自https://github.com/lib/pq/issues/65

  

by dpapathanasiou :   我已经弄明白了这个问题;这不是pq中的错误,而是我的方式   正在创建准备好的语句:我需要使用($ 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)")