首页 » PostgreSQL, 开发语言 » Go语言(GO lang)连接PostgreSQL Database使用pq

Go语言(GO lang)连接PostgreSQL Database使用pq

Go语言(GO lang)连接Oracle Database使用godror》上篇以后,这里继续测试使用GO Lang操作PostGreSQL, 使用pq驱动。

1,安装posgresql go驱动

# go get github.com/lib/pq

2, 准备postgresql 表

sdbo=# select version()
sdbo-# ;
 PostgreSQL 13.1, compiled by Visual C++ build 1914, 64-bit

weejar=# \c sdbo
您现在已经连接到数据库 "sdbo",用户 "weejar".
sdbo=# create table sdbo_department(dep_id int,dep_name varchar(30));
CREATE TABLE
sdbo=#
sdbo=# \dt+
 public   | sdbo_department | 数据表 | weejar | permanent   | 0 bytes |

sdbo=# \d sdbo_department
 dep_id   | integer               |          |        |
 dep_name | character varying(30) |          |        |

3, Go Lang代码

package main

import (
	"database/sql"
	"fmt"
	"log"
	_ "github.com/lib/pq"
)

const (
	host     = "localhost"
	port     = 5432
	user     = "weejar"
	password = "weejar"
	dbname   = "sdbo"
)

func connectDB() *sql.DB{
	psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
		"password=%s dbname=%s sslmode=disable",
		host, port, user, password, dbname)

	db, err := sql.Open("postgres", psqlInfo)
	if err != nil {
		panic(err)
	}

	err = db.Ping()
	if err != nil {
		panic(err)
	}
	fmt.Println("Successfully connected!")
	return db
}

func insertUser(db *sql.DB)  {
	stmt,err := db.Prepare("insert into sdbo_department(dep_id,dep_name) values($1,$2)")
	if err != nil {
		log.Fatal(err)
	}
	_,err = stmt.Exec(1,"mgr")
	
	if err != nil {
		log.Fatal(err)
	}else {
			fmt.Println("insert into sdbo_department success!")
	}

}

func query(db *sql.DB){
	var id,name string
    

	rows,err:=db.Query(" select * from sdbo_department where dep_id=$1","1")

	if err!= nil{
		fmt.Println(err)
	}
	defer rows.Close()

	for rows.Next(){
		err:= rows.Scan(&id,&name)

		if err!= nil{
			fmt.Println(err)
		}
	}

	err = rows.Err()
	if err!= nil{
		fmt.Println(err)
	}

	fmt.Println(id,name)
}

func main()  {
	db:=connectDB()
	insertUser(db)
	query(db)

}

4, 执行 GO 代码

D:\code\gotest>go run connectpg.go
Successfully connected!
insert into sdbo_department success!
1 mgr

— enjoy —

打赏

对不起,这篇文章暂时关闭评论。