数据库
首页 > 数据库> > golang连接postgresql数据库

golang连接postgresql数据库

作者:互联网

PostgreSQL和MySQL比较,它更加庞大一点,因为它是用来替代Oracle而设计的。所以在企业应用中采用PostgreSQL是一个明智的选择。

1, 获取数据库驱动
go get https://github.com/bmizerany/pq

2, 创建数据库表
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);

3, Go操作数据库表数据相关代码(增删改查)

package main

import (
“database/sql”
“fmt”
_ “github.com/bmizerany/pq
)

func main() {
db, err := sql.Open(“postgres”, “user=test password=test dbname=test sslmode=disable”)
checkErr(err)

//插入数据
stmt, err := db.Prepare("INSERT INTO userinfo(username,departname,created) VALUES($1,$2,$3) RETURNING uid")
checkErr(err)

res, err := stmt.Exec("astaxie", "研发部门", "2012-12-09")
checkErr(err)
id, err := res.LastInsertId()
checkErr(err)

fmt.Println(id)

//更新数据
stmt, err = db.Prepare("update userinfo set username=$1 where uid=$2")
checkErr(err)

res, err = stmt.Exec("astaxieupdate", 1)
checkErr(err)

affect, err := res.RowsAffected()
checkErr(err)

fmt.Println(affect)

//查询数据
rows, err := db.Query("SELECT * FROM userinfo")
checkErr(err)

for rows.Next() {
    var uid int
    var username string
    var department string
    var created string
    err = rows.Scan(&uid, &username, &department, &created)
    checkErr(err)
    fmt.Println(uid)
    fmt.Println(username)
    fmt.Println(department)
    fmt.Println(created)
}

//删除数据
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(affect)

db.Close()

}

func checkErr(err error) {
if err != nil {
panic(err)
}
}
深圳网站建设:https://www.sz886.com

标签:postgresql,checkErr,err,数据库,db,golang,Println,fmt,uid
来源: https://blog.csdn.net/chenmh12/article/details/89675941