golang的增删改查
整体的步骤都是先通过func (db *DB) Prepare(query string) (Stmt, error)得到Stmt
然后执行exec或者query数据库操作
func (s *Stmt) Exec(query string, args …interface{}) (Result, error) //增删改
func (s *Stmt) Query(args …interface{}) (*Rows, error)//查
package main
import (
"database/sql"
"fmt"
_ "github.com/godror/godror"
)
var db *sql.DB
const (
host = "192.168.1.11"
port = 1521
user = "system"
sqlpassword = "manager"
dbname = "peixun"
)
func initsql(){
osqlInfo := fmt.Sprintf("%s/%s@%s:%d/%s", user, sqlpassword, host, port, dbname)
DB, err := sql.Open("godror", osqlInfo)
if err != nil {
panic(err)
}
err = DB.Ping()
if err != nil {
panic(err)
}
db = DB
fmt.Println("链接成功")
}
func add() {
//增加
//这里的:a,:b,:c都是占位符,只要不同即可,实际值是后面exec中的入参
sqlStatement:="insert into table_text(AAA,BBB,CCC) values(:a,:b,:c)"
stmt,err :=db.Prepare(sqlStatement)
defer stmt.Close()
if err!= nil{
panic(err)
}
_,err=stmt.Exec("a","b","c")
if err!=nil{
panic(err)
}
fmt.Println("添加成功")
}
func delete() {
//删除
sqlStatement := "DELETE FROM table_text WHERE aaa=:a"
stmt, err := db.Prepare(sqlStatement)
defer stmt.Close()
if err != nil {
panic(err)
}
_, err = stmt.Exec("a")
if err != nil {
panic(err)
}
}
func update() {
//更改
sqlStatement := "UPDATE table_text SET bbb=:x1 WHERE aaa=:x2"
stmt, err := db.Prepare(sqlStatement)
defer stmt.Close()
if err != nil {
panic(err)
}
_, err = stmt.Exec("bb", "a")
if err != nil {
panic(err)
}
fmt.Println("update")
}
func selectA(){
//查找
sqlStatement := "SELECT aaa,bbb,ccc,ddd FROM table_text WHERE aaa=:x1"
stmt, err := db.Prepare(sqlStatement)
defer stmt.Close()
if err != nil {
panic(err)
}
rows, err := stmt.Query("a")
defer rows.Close()
if err != nil {
panic(err)
}
tt_list := []table_text{} //创建一个没有长度和容量的切片,用来存储查询到的数据
tt_row := table_text{} //创建一个空的对象用于在循环中临时存放查询到的数据。
for rows.Next() {
rows.Scan(&tt_row.aaa, &tt_row.bbb,&tt_row.ccc,&tt_row.ddd)
tt_list = append(tt_list, tt_row)
}
fmt.Println(tt_list)
}
type table_text struct{
aaa string;
bbb string;
ccc string;
ddd int64;
}
func main(){
initsql()
add()
//update()
selectA()
//delete()
defer db.Close()
}