Go语言操作mysql数据库简单例子
go语言操作数据库非常的简单,
他也有一个类似jdbc的东西"database/sql"
实现类是"github.com/go-sql-driver/mysql"
使用过jdbc的人应该一看就懂
对日期的处理比较晦涩,没有java流畅:
package main
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"log"
"time"
)
/*
create table t(
id int primary key auto_increment,
name varchar(20) not null,
ts timestamp
);
*/
func insert(db *sql.db) {
stmt, err := db.prepare("insert into t(name,ts) values(?,?)")
defer stmt.close()
if err != nil {
log.println(err)
return
}
ts, _ := time.parse("2006-01-02 15:04:05", "2014-08-28 15:04:00")
stmt.exec("edmond", ts)
}
func main() {
db, err := sql.open("mysql", "xx:xx@tcp(127.0.0.1:3306)/mvbox?charset=utf8")
if err != nil {
log.fatalf("open database error: %s\n", err)
}
defer db.close()
err = db.ping()
if err != nil {
log.fatal(err)
}
insert(db)
rows, err := db.query("select id,name,ts from t where id>?", 1)
if err != nil {
log.println(err)
}
defer rows.close()
var id int
var name string
var ts string
for rows.next() {
err := rows.scan(&id, &name,&ts)
if err != nil {
log.fatal(err)
}
log.println(id, name,ts)
}
err = rows.err()
if err != nil {
log.fatal(err)
}
}