下载: http://github.com/go-sql-driver/mysql
import(
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
func main(){
//连接数据库
db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/test?charset=utf8")
if err != nil {
panic(err)
}
//增加数据
stmt, err := db.Prepare(`INSERT student (name,age) values (?,?)`)
res, err := stmt.Exec("wangwu", 26)
id, err := res.LastInsertId()
fmt.Println("自增id=", id)
//修改数据
stmt, err := db.Prepare(`UPDATE student SET age=? WHERE id=?`)
res, err := stmt.Exec(21, 5)
num, err := res.RowsAffected() //影响行数
fmt.Println(num)
//删除数据
stmt, err := db.Prepare(`DELETE FROM student WHERE id=?`)
res, err := stmt.Exec(5)
num, err := res.RowsAffected()
fmt.Println(num)
//查询数据
rows, err := db.Query("SELECT * FROM student")
for rows.Next() {
var userId int
var userName string
var userAge int
var userSex int
rows.Columns()
err = rows.Scan(&userId, &userName, &userAge, &userSex)
checkErr(err)
fmt.Println(userId)
fmt.Println(userName)
fmt.Println(userAge)
fmt.Println(userSex)
}
}