package main
import (
"database/sql"
"fmt"
)
type Student struct {
Id int64
Name string
Age int
}
func ConnectDB() (db *sql.DB, err error) {
dbDriver := "mysql"
dbUser := "root"
dbPass := "nilpointer.net"
dbName := "nilpointer_db"
db, err = sql.Open(dbDriver, dbUser+":"+dbPass+"@/"+dbName)
return
}
func main() {
db, err := ConnectDB()
if err != nil {
fmt.Println(err)
} else {
keyword := "nilpointer.net"
rows, err2 := db.Query("select * from student where name like ?", "%" + keyword + "%")
if err2 != nil {
fmt.Println(err2)
} else {
students := []Student{}
for rows.Next() {
var student Student
err3 := rows.Scan(&student.Id, &student.Name, &student.Age)
if err3 != nil {
fmt.Println(err3)
} else {
students = append(students, student)
}
}
fmt.Println(students)
}
}
}