標籤:date nbsp userinfo localhost fico 開發 integer .exe 連接埠
先在PostgreSQL資料庫中建一個表,可以使用PostgreSQL官方的pgAdmin來完成:
CREATE TABLE userinfo( uid serial NOT NULL, username character varying(100) NOT NULL, departname character varying(500) NOT NULL, Created date, CONSTRAINT userinfo_pkey PRIMARY KEY (uid))WITH (OIDS=FALSE);CREATE TABLE userdeatail( uid integer, intro character varying(100), profile character varying(100))WITH(OIDS=FALSE);
然後運行以下代碼,實現串連資料庫和增刪查改,請自行更改參數配置部分:
package mainimport ("database/sql""fmt"_ "github.com/lib/pq")var db *sql.DBfunc sqlOpen() {var err errordb, err = sql.Open("postgres", "port=5433 user=postgres password=123456 dbname=ficow sslmode=disable")//port是資料庫的連接埠號碼,預設是5432,如果改了,這裡一定要自訂;//user就是你資料庫的登入帳號;//dbname就是你在資料庫裡面建立的資料庫的名字;//sslmode就是安全驗證模式;//還可以是這種方式開啟//db, err := sql.Open("postgres", "postgres://pqgotest:[email protected]/pqgotest?sslmode=verify-full")checkErr(err)}func sqlInsert() {//插入資料stmt, err := db.Prepare("INSERT INTO userinfo(username,departname,created) VALUES($1,$2,$3) RETURNING uid")checkErr(err)res, err := stmt.Exec("ficow", "軟體開發部門", "2017-03-09")//這裡的三個參數就是對應上面的$1,$2,$3了checkErr(err)affect, err := res.RowsAffected()checkErr(err)fmt.Println("rows affect:", affect)}func sqlDelete() {//刪除資料stmt, err := db.Prepare("delete from userinfo where uid=$1")checkErr(err)res, err := stmt.Exec(1)checkErr(err)affect, err := res.RowsAffected()checkErr(err)fmt.Println("rows affect:", affect)}func sqlSelect() {//查詢資料rows, err := db.Query("SELECT * FROM userinfo")checkErr(err)println("-----------")for rows.Next() {var uid intvar username stringvar department stringvar created stringerr = rows.Scan(&uid, &username, &department, &created)checkErr(err)fmt.Println("uid = ", uid, "\nname = ", username, "\ndep = ", department, "\ncreated = ", created, "\n-----------")}}func sqlUpdate() {//更新資料stmt, err := db.Prepare("update userinfo set username=$1 where uid=$2")checkErr(err)res, err := stmt.Exec("ficow", 1)checkErr(err)affect, err := res.RowsAffected()checkErr(err)fmt.Println("rows affect:", affect)}func sqlClose() {db.Close()}func checkErr(err error) {if err != nil {panic(err)}}func sqlTest() {sep := "----------\n"sqlOpen()println(sep, "*sqlOpen")sqlSelect()println(sep, "*sqlSelect")sqlInsert()sqlSelect()println(sep, "*sqlInsert")sqlUpdate()sqlSelect()println(sep, "*sqlUpdate")sqlDelete()sqlSelect()println(sep, "*sqlDelete")sqlClose()println(sep, "*sqlClose")}func main() {sqlTest()}
相關連結:
可以查看這個驅動庫的文檔進行學習: https://godoc.org/github.com/lib/pq
另外,還要感謝這位作者的教程: http://www.cnblogs.com/songxingzhu/p/5024517.html
轉載請註明出處:http://www.cnblogs.com/ficow/p/6537238.html ,謝謝!
Go 串連PostgreSQL資料庫