- 5.访问数据库
- 5.1 database/sql接口
- 5.2 使用MySQL数据库
- 5.3 使用SQLite数据库
- 5.4 使用PostgreSQL数据库
- 5.5 使用Beego orm库进行ORM开发
- 5.6 NOSQL数据库操作
- 5.7 小结
package main import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" ) func main() { db, err := sql.Open("mysql", "beego:beego_pass@tcp(10.25.27.92:3306)/PrismLogDB?charset=utf8") checkErr(err) stmt, err := db.Prepare("INSERT userinfo SET username=?, departname=?,created=?") checkErr(err) res, err := stmt.Exec("astaxie", "研发部门", "2012-12-19") checkErr(err) res, err = stmt.Exec("chengang", "研发部门", "2017-12-19") checkErr(err) id, err := res.LastInsertId() checkErr(err) fmt.Println(id) stmt, err = db.Prepare("update userinfo set username=? where uid=?") checkErr(err) res, err = stmt.Exec("astaxieupdate", id) checkErr(err) affect, err := res.RowsAffected() checkErr(err) fmt.Println(affect) rows, err := db.Query("SELECT * FROM userinfo") checkErr(err) for rows.Next() { var uid int var username string var department string var created string err = rows.Scan(&uid, &username, &department, &created) checkErr(err) fmt.Println(uid) fmt.Println(username) fmt.Println(department) fmt.Println(created) } stmt, err = db.Prepare("delete from userinfo where uid=?") checkErr(err) res, err = stmt.Exec(id) checkErr(err) affect, err = res.RowsAffected() checkErr(err) fmt.Println(affect) db.Close() } func checkErr(err error) { if err != nil { panic(err) } }