来源:未知 时间:2018-08-31 17:43 作者:小飞侠 阅读:次
[导读] packagemainimport(fmtdatabase/sql_github.com/go-sql-driver/mysqllog)var(IdstringNamestring)funcmain(){db,err:=sql.Open(mysql,root:123456@tcp(127.0.0.1:3306)/go?charset=utf8)iferr!=nil{fmt.Println(err)return}deferdb.Close()update(db)sqlselec...
package main import( "fmt" "database/sql" _ "github.com/go-sql-driver/mysql" "log" ) var ( Id string Name string ) func main(){ db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/go?charset=utf8") if err != nil { fmt.Println(err) return } defer db.Close() update(db) sqlselect(db) insert(db) fmt.Println("插入后") sqlselect(db) delete(db); fmt.Println("删除后") sqlselect(db) } // 查询 数据 func sqlselect(db *sql.DB) { rows,err := db.Query("select * from test") if err != nil { fmt.Println("数据库查询出错执行出错") } for rows.Next(){ //按表名的顺序读取参数 err := rows.Scan(&Name,&Id) if err != nil { log.Fatal(err) } fmt.Println(Name, Id) } rows.Close() } //更新 func update(db *sql.DB) { result,err:=db.Exec("update test set Id = 1123 WHERE test.Name=?","a") if err != nil { fmt.Println("数据库执行更新出错") } changelow,err:=result.RowsAffected() if err != nil { } fmt.Println("共计",changelow,"行受到影响") } //INSERT INTO `go`.`test` (`Id`, `Name`) VALUES ('4', 'd'); //插入 func insert(db *sql.DB){ result,err:=db.Exec("INSERT test (Id, Name) VALUES (?,?)","5","e") if err != nil { fmt.Println("数据库执行插入出错",err) return } changelow,err:=result.RowsAffected() if err != nil { } fmt.Println("共计",changelow,"行受到影响") } //DELETE FROM `go`.`test` WHERE `Id` = '5'; //删除第5条数据 func delete(db *sql.DB){ result,err:=db.Exec("DELETE FROM test WHERE `Id` = ?",5) if err != nil { fmt.Println("数据库执行删除出错",err) return } changelow,err := result.RowsAffected() if err != nil { } fmt.Println("共计",changelow,"行受到影响") } 贴出 创建sql的数据 CREATE TABLE `test` ( `Id` int(11) NOT NULL, `Name` char(200) DEFAULT NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 msq的 url 规则 user@unix(/path/to/socket)/dbname root:pw@unix(/tmp/mysql.sock)/myDatabase?loc=Local user:password@tcp(localhost:5555)/dbname?tls=skip-verify&autocommit=true |
自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习
京ICP备14009008号-1@版权所有www.zixuephp.com
网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com