一、記得要開啓服務git
pg_ctl -D /usr/local/var/postgres start
否則會出現github
➜ 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"?
二、在terminal中運行的SQL語句用的雙引號是' '。sql
而後關於sqlx包vim
db.Exec,執行的Query只是那些insert多。由於其是沒返回值的。dom
返回一個lastInsertIndex-----這個在postgresql中是沒用的,還有一個就是rowsAffect。因此,恩。socket
stmt, err := db.Prepare()也是同樣,stmt.Exec是返回sql.result的 ide
//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)
三、用sql.Query就不是了,返回的是sql.rows函數
還能夠用來執行insert呢post
四、一個模板ui
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) } }