golang訪問數(shù)據(jù)庫記錄SQL語句:
使用的包為:
1:github.com/arthurkiller/rollingwriter //寫入日志包
2: github.com/go-xorm/xorm //xorm包
具體實現(xiàn)為:
package main
import (
"time"
"github.com/arthurkiller/rollingwriter"
_ "github.com/go-sql-driver/mysql"
"github.com/go-xorm/xorm"
)
func main() {
var conn string = "root:123456@tcp(127.0.0.1)/logsdemo?charset=utf-8"
Engine, err := xorm.NewEngine("mysql", conn)
if err != nil {
panic("mysql connect fail")
}
config := rollingwriter.Config{
LogPath: "./logs", //日志路徑
TimeTagFormat: "060102150405", //時間格式串
FileName: "mysql_exec", //日志文件名
MaxRemain: 3, //配置日志最大存留數(shù)
RollingPolicy: rollingwriter.VolumeRolling, //配置滾動策略 norolling t
imerolling volumerolling
RollingTimePattern: "* * * * * *", //配置時間滾動策略
RollingVolumeSize: "1M", //配置截斷文件下限大小
WriterMode: "none",
BufferWriterThershould: 256,
// Compress will compress log file with gzip
Compress: true,
}
writer, err := rollingwriter.NewWriterFromConfig(config)
if err != nil {
panic(err)
}
var logger *xorm.SimpleLogger = xorm.NewSimpleLogger(writer)
Engine.SetLogger(logger)
Engine.ShowSQL(true)
logger.Info("ts info code")
Engine.Exec("select * from cp_order where id = ? ", 3)
time.Sleep(1 * time.Second)
}
rollingwriter 實現(xiàn)一個 io.Writer傳入到xorm.NewSimpleLogger 中 在xorm中實現(xiàn)日志的寫入,在rollingwriter中保存日志到文件中
依賴包:https://github.com/robfig/cron
補充: golang xorm Model 模型文件模板
* Record.go
package models
import (
"fmt"
"github.com/go-xorm/xorm"
"time"
)
// 用戶首次登錄
type FirstLoginRecord struct {
Id int64 `xorm:"not null pk autoincr INT(11)"`
UserID int64 `json:"userid" xorm:"int(11) not null 'userid'"`
IP string `json:"logonip" xorm:"varchar(45) not null 'logonip'"`
CreatedAt time.Time `json:"logontime" xorm:"timestamp not null 'logontime'"`
UpdatedAt time.Time `json:"logofftime" xorm:"timestamp not null 'logofftime'"`
Source int `json:"source" xorm:"tinyint(3) not null"`
IsCharged int `json:"ischargeaccount" xorm:"tinyint(3) unsigned not null 'ischargeaccount'"`
}
func (*FirstLoginRecord) TableName() string {
return "W_UserFirstLogonRec"
}
func (*FirstLoginRecord) DB() *xorm.Engine {
return DbDefault()
}
func (t *FirstLoginRecord) Save() error {
var err error
var engine = t.DB()
if t.Id == 0 {
t.Id, err = engine.Insert(t)
return err
}
var rowsAffected int64
rowsAffected, err = engine.Id(t.Id).Update(t)
fmt.Printf("@table: %s: %d rows affected", t.TableName(), rowsAffected)
return err
}
// 用戶id唯一約束
func (this *FirstLoginRecord) AddDistinct() error {
var err error
var engine = this.DB()
var has bool
var ent = FirstLoginRecord{UserID: this.UserID }
has, err = engine.Get(ent)
if has {
return nil
}
this.Id, err = engine.Insert(this)
return err
}
http://www.xorm.io/docs/
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
您可能感興趣的文章:- 在golang xorm中使用postgresql的json,array類型的操作
- golang xorm及time.Time自定義解決json日期格式的問題
- go語言 xorm框架 postgresql 的用法及詳細注解
- golang中xorm的基本使用說明
- 解決goxorm無法更新值為默認值的問題
- xorm根據(jù)數(shù)據(jù)庫生成go model文件的操作
- 使用go xorm來操作mysql的方法實例
- go xorm框架的使用