通过写go语言函数,使用工具函数连接数据库
func MySQLconn() *sql.DB {
db, err := sql.Open(“mysql”, “root:root@tcp(localhost:3306)/studytest”)
if err != nil {
fmt.Println(err)
}
fmt.Println(db)
return db
}
go语言MySQL数据库进行查询所有
func MyQuery() {
db := MySQLconn()
sqls := “select *from mytest”
rows, _ := db.Query(sqls)
var id, name string
for rows.Next() {
rows.Scan(&id, &name)
fmt.Println(id, name)
}
}
go语言MySQL数据库进行插入数据
func MyInsert() {
db := MySQLconn()
stmt, _ := db.Prepare(“insert into mytest values (?,?)”)
result, _ := stmt.Exec(“111”, “aa”)
fmt.Println(result)
}
go语言MySQL数据库进行删除数据
func MyDelete() {
db := MySQLconn()
sqlstmt := “delete from mytest where id=?”
stmt, _ := db.Prepare(sqlstmt)
result, _ := stmt.Exec(“333”)
fmt.Println(result)
}
go语言MySQL数据库进行
func MySQLUpdate() {
db := MySQLconn()
sqlstmt := “update mytest set name=’wilson’ where id=?”
stmt, _ := db.Prepare(sqlstmt)
stmt.Exec(“111”)
}