Go语言学习笔记

114 阅读1分钟

数据库学习

以mysql为例,首先需要在govendor中导入包

govendor的使用放个链接www.cnblogs.com/shockerli/p…

database/sql

github.com/go-sql-driver/mysql

第一步需要连接数据库,以用户名root,密码191513为例

//DSN数据源字符串:用户名:密码@协议(地址:端口)/数据库?参数=参数值
db, err := sql.Open("mysql", "root:191513@tcp(localhost:3306)/studentgo?charset=utf8")

第二步为写各种增删改查的sql语句,我选择放进func里

insert例子,这里插入到数据库的是student结构体

func Insert(db *sql.DB ,student Student){   
stmt, err := db.Prepare("INSERT INTO student(xm, xh ,xb ,bj) VALUES(?, ?, ?, ?)")   
defer stmt.Close()  
 if err != nil {      
log.Println(err)     
 return   }   
stmt.Exec()   
stmt.Exec(student.xm, student.xh,student.xb,student.bj)
}