创建MySQL表
CREATE TABLE `atest` (
`c1` bigint(25) NOT NULL,
`c2` varchar(50) DEFAULT NULL,
`c3` varchar(50) DEFAULT NULL,
PRIMARY KEY (`c1`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Go脚本
package main
import (
"fmt"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
type TestMysql struct {
db *sql.DB
}
/* 初始化数据库引擎 */
func Init() (*TestMysql,error){
test := new(TestMysql);
db,err := sql.Open("mysql","root:123456@tcp(127.0.0.1:3306)/dxt?charset=utf8");
if err!=nil {
fmt.Println("database initialize error : ",err.Error());
return nil,err;
}
test.db = db;
return test,nil;
}
/* 测试数据库数据添加 */
func (test *TestMysql)Create(){
if test.db==nil {
return;
}
stmt,err := test.db.Prepare("insert into atest(c1,c2,c3)values(?,?,?)");
if err!=nil {
fmt.Println(err.Error());
return;
}
defer stmt.Close();
if result,err := stmt.Exec(1,"张三","北京");err==nil {
if id,err := result.LastInsertId();err==nil {
fmt.Println("insert id : ",id);
}
}
if result,err := stmt.Exec(2,"李四","上海");err==nil {
if id,err := result.LastInsertId();err==nil {
fmt.Println("insert id : ",id);
}
}
if result,err := stmt.Exec(3,"王五","杭州");err==nil {
if id,err := result.LastInsertId();err==nil {
fmt.Println("insert id : ",id);
}
}
}
func (test *TestMysql)Close(){
if test.db!=nil {
test.db.Close();
}
}
func main(){
if test,err := Init();err==nil {
test.Create();
test.Close();
}
}
查看MySQL中写入的数据