使用go脚本向MySQL表中写入数据
生活随笔
收集整理的這篇文章主要介紹了
使用go脚本向MySQL表中写入数据
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
為什么80%的碼農都做不了架構師?>>> ??
創建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 mainimport ("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中寫入的數據
轉載于:https://my.oschina.net/siiiso/blog/852839
總結
以上是生活随笔為你收集整理的使用go脚本向MySQL表中写入数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: r指定位置插入一列数值
- 下一篇: CHIL-ORACLE-唯一约束(uni