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 {
student := Student{
Name: "Name 1",
Age: 20,
}
result, err2 := db.Exec("insert into student(name, age) values(?, ?)", student.Name, student.Age)
if err2 != nil {
fmt.Println("Failed")
} else {
student.Id, _ = result.LastInsertId()
rowsAffected, _ := result.RowsAffected()
fmt.Println("id:", student.Id)
fmt.Println("Rows Affected:", rowsAffected)
}
}
}