1、记得要开启服务
pg_ctl -D /usr/local/var/postgres start
不然会出现
➜ bin psql book psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"?
2、在terminal中运行的SQL语句用的双引号是' '。
然后关于sqlx包
db.Exec,执行的Query只是那些insert多。因为其是没返回值的。
返回一个lastInsertIndex-----这个在postgresql中是没用的,还有一个就是rowsAffect。所以,恩。
stmt, err := db.Prepare()也是一样,stmt.Exec是返回sql.result的
//pg不支持这个函数,因为他没有类似MySQL的自增ID // id, err := res.LastInsertId() // checkErr(err) // fmt.Println(id) var lastInsertId int err = db.QueryRow("INSERT INTO userinfo(username,departname,created) VALUES($1,$2,$3) returning uid;", "astaxie", "研发部门", "2012-12-09").Scan(&lastInsertId) checkErr(err) fmt.Println("最后插入id =", lastInsertId)
3、用sql.Query就不是了,返回的是sql.rows
还可以用来执行insert呢
4、一个模板
package main import ( "fmt" "log" "github.com/jmoiron/sqlx" _ "github.com/lib/pq" ) func connDatabase(databaseTypeName string, user string, password string, databaseName string) *sqlx.DB { db, err := sqlx.Open(databaseTypeName, "user="+user+" password="+password+" dbname="+databaseName+" sslmode=disable") checkError(err, "open database") return db } func main() { db := connDatabase("postgres", "vimi", "stupidone", "test") defer db.Close() result, err := db.Exec("select * from story") fmt.Println(result.RowsAffected()) checkError(err, "select") rows, err := db.Queryx("select * from story") checkError(err, "Queryx") for rows.Next() { var createUser, url, createDate string err := rows.Scan(&createUser, &url, &createDate) checkError(err, "rows") fmt.Println(createUser) fmt.Println(url) fmt.Println(createDate) } // stmt, err := db.Prepare("select * from story") // defer stmt.Close() // checkError(err, "stmt") //and also can this rr, err := db.Queryx("insert into story(create_user, url, create_date) values($1, $2, $3)", "jack", "google.com", "yesterday") fmt.Println(rr) checkError(err, "insert") } func checkError(err error, name string) { if err != nil { log.Fatal(err.Error() + " ---- " + name) } }