package main
import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" )
func main() { db, _ := sql.Open("mysql", "root:root@(127.0.0.1:3306)/itcast") defer db.Close() err := db.Ping() if err != nil { fmt.Println("数据库连接错误") }
//新增数据 sql := "insert into stu value(1,'张三')" result, _ := db.Exec(sql) fmt.Printf("%t", result)
//预处理 stuStr := [2][2]string{{"2", "张三"}, {"3", "李四"}} stmt, _ := db.Prepare("insert into stu value (?,?)") for _, s := range stuStr { stmt.Exec(s[0], s[1]) }
//当行查询 var id, name string row := db.QueryRow("select * from stu where id=3") row.Scan(&id, &name) fmt.Println("id:=", id, "name:=", name)
//多行查询 var ids, names string rows, _ := db.Query("select * from stu") for rows.Next() { rows.Scan(&ids, &names) fmt.Println("----------------") fmt.Println("ids:=", ids, "names:=", names) } }
|
请发表评论