插入
package mainimport ("database/sql""fmt"_ "github.com/lib/pq")const (host= "localhost"port= 5432user= "postgres"password = "wangshubo123"dbname= "test")type Teacher struct {IDintAge int}func main() {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)}defer db.Close()err = db.Ping()if err != nil {panic(err)}fmt.Println("Successfully connected!")sqlStatement := `INSERT INTO teacher (id, age)VALUES ($1, $2)RETURNING id`id := 3err = db.QueryRow(sqlStatement, 3, 19).Scan(&id)if err != nil {panic(err)}fmt.Println("New record ID is:", id)}再运行一次 , 错误:panic: pq: 重复键违反唯一约束”teacher_pkey”
查询
package mainimport ("database/sql""fmt"_ "github.com/lib/pq")const (host= "localhost"port= 5432user= "postgres"password = "wangshubo123"dbname= "test")type Teacher struct {IDintAge int}func main() {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)}defer db.Close()err = db.Ping()if err != nil {panic(err)}fmt.Println("Successfully connected!")sqlStatement := `SELECT * FROM teacher WHERE id=$1;`var teacher Teacherrow := db.QueryRow(sqlStatement, 1)err = row.Scan(&teacher.ID, &teacher.Age)switch err {case sql.ErrNoRows:fmt.Println("No rows were returned!")returncase nil:fmt.Println(teacher)default:panic(err)}}
推荐阅读
- 操作系统学习 让启动镜像支持Fat12文件格式
- 用哪种语言写的应用漏洞最严重?六大主流语言代码漏洞分析出炉
- 3 种使用 PostgreSQL 命令的方式
- Windows 10快速使用的几个技巧,让你的操作更快捷
- 盘点各编程语言的应用领域
- 使用Python+Fabric实现Linux自动化操作
- 高级语言中的语句在汇编中是如何实现的
- 真香!Python十大常用文件操作,轻松办公
- 电脑指纹怎么设置?按照以下步骤操作,轻松设置指纹锁
- MySQL的 join 操作弱爆了?
