package main import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" ) func main() { // 打开连接 db, err := sql.Open("mysql", "root:121719abc@tcp(localhost:3306)/first") db.Ping() defer func() { if db != nil { db.Close() } }() if err != nil { fmt.Println("数据连接失败") return } //执行预处理 stmt, err := db.Prepare("insert into people values (default,?,?)") //新增语句 stmt2, err := db.Prepare("update people set name = ?,address=? where id = ?") //修改语句 //stmt3,err := db.Prepare("delete from people where id = ?") // 删除语句 stmt4, err := db.Prepare("select * from people") defer func() { if stmt != nil { stmt.Close() } if stmt2 != nil { stmt.Close() } }() if err != nil { fmt.Println("预处理失败") return } r, err := stmt.Exec("张三", "临沂") r2, err := stmt2.Exec("张四", "潍坊", 3) rows, err := stmt4.Query() defer func() { if rows != nil { rows.Close() } }() if err != nil { fmt.Println("sql处理失败") return } //获取结果 count, err := r.RowsAffected() count2, err := r2.RowsAffected() if err != nil { fmt.Println("结果获取失败") } if count > 0 { fmt.Println("新增成功") } else { fmt.Println("新增失败") } if count2 > 0 { fmt.Println("修改成功") } else { fmt.Println("修改失败") } for rows.Next() { var id int var name string var adddress string rows.Scan(&id, &name, &adddress) fmt.Println(id, name, adddress) } }
go 语言操作数据库
最新推荐文章于 2024-10-30 18:24:49 发布