• beegoormsqlite


    dao.go

    ```

    package dao

    import (
    "fmt"
    "github.com/astaxie/beego/orm"
    "html"
    "strings"
    "sync"
    )

    //constant metatable name reference
    const (
    MetaTableName = "meta"
    )

    // Meta metadata object
    type Meta struct {
    Key string `orm:"column(key); size(256); pk"`
    Type string `orm:"column(type); size(32)"`
    Value string `orm:"column(value); null; type(text)"`
    }

    type User struct {
    UserId int `orm:"column(user_id); size(256); pk"`
    UserName string `orm:"column(user_name); size(32)"`
    UserPwd string `orm:"column(user_pwd); size(32);"`
    UserPhone string `orm:"column(user_phone); size(32)"`
    UserQQ string `orm:"column(user_qq); size(32);"`
    UserCity string `orm:"column(user_city); size(32)"`
    }

    type UserExtra struct {
    UserPhone string `orm:"column(user_phone); size(32)"`
    UserQQ string `orm:"column(user_qq); size(32);"`
    UserCity string `orm:"column(user_city); size(32)"`
    }



    // DBAccess is Ormer object interface for all transaction processing and switching database
    var DBAccess orm.Ormer
    var once sync.Once

    // InitDBConfig Init DB info
    func InitDBConfig(driverName, dbName, dataSource string) {
    once.Do(func() {
    if err := orm.RegisterDriver(driverName, orm.DRSqlite); err != nil {
    fmt.Errorf("Failed to register driver: %v", err)
    }
    if err := orm.RegisterDataBase(
    dbName,
    driverName,
    dataSource); err != nil {
    fmt.Errorf("Failed to register db: %v", err)
    }
    // os.Chmod(dataSource, 0400)
    // sync database schema
    if err := orm.RunSyncdb(dbName, false, true); err != nil {
    fmt.Errorf("run sync db error %v", err)
    }
    // create orm
    DBAccess = orm.NewOrm()
    if err := DBAccess.Using(dbName); err != nil {
    fmt.Errorf("Using db access error %v", err)
    }
    })
    }

    // SaveMeta save meta to db
    func SaveMeta(meta *Meta) error {
    meta.Value = html.EscapeString(meta.Value)
    _, err := DBAccess.Insert(meta)
    if err == nil || IsNonUniqueNameError(err) {
    return nil
    }
    return err
    }

    // IsNonUniqueNameError tests if the error returned by sqlite is unique.
    // It will check various sqlite versions.
    func IsNonUniqueNameError(err error) bool {
    str := err.Error()
    if strings.HasSuffix(str, "are not unique") || strings.Contains(str, "UNIQUE constraint failed") || strings.HasSuffix(str, "constraint failed") {
    return true
    }
    return false
    }

    //// DeleteMetaByKey delete meta by key
    //func DeleteMetaByKey(key string) error {
    //
    // _, err := DBAccess.QueryTable(MetaTableName).Filter("key", key).Delete()
    // return err
    //}
    //func DeleteMetaByType(typeStr string) error {
    // _, err := DBAccess.QueryTable(MetaTableName).Filter("type", typeStr).Delete()
    // return err
    //}
    //
    //// UpdateMeta update meta
    //func UpdateMeta(meta *Meta) error {
    // meta.Value = html.EscapeString(meta.Value)
    // _, err := DBAccess.Update(meta) // will update all field
    // return err
    //}

    // InsertOrUpdate insert or update meta
    func InsertOrUpdate(user *User) error {
    _, err := DBAccess.Raw("INSERT OR REPLACE INTO users (user_id, user_name, user_pwd, user_phone, user_qq, user_city) VALUES (?,?,?,?,?,?)", user.UserId, user.UserName, user.UserPwd, user.UserPhone,user.UserQQ, user.UserCity).Exec() // will update all field
    return err
    }

    // InsertOrUpdate insert or update meta
    //func InsertOrUpdate(user *UserModel) error {
    // _, err := DBAccess.Raw("INSERT OR REPLACE INTO users (user_id, user_name, user_pwd) VALUES (?,?,?)", user.UserId, user.UserName, user.UserPwd).Exec() // will update all field
    // return err
    //}

    //// QueryMeta return only meta's value, if no error, Meta not null
    //func QueryMeta(key string, condition string) (*[]string, error) {
    // meta := new([]Meta)
    // _, err := DBAccess.QueryTable(MetaTableName).Filter(key, condition).All(meta)
    // if err != nil {
    // return nil, err
    // }
    //
    // var result []string
    // for _, v := range *meta {
    // result = append(result, html.UnescapeString(v.Value))
    // }
    // return &result, nil
    //}

    ```

    main.go

    ```

    package main

    import (
    "dbTest/work/dao"
    "fmt"
    "github.com/astaxie/beego/orm"
    "sync"
    "time"


    //Blank import to run only the init function
    _ "github.com/mattn/go-sqlite3"
    )

    func main() {

    //defer func() {
    // if r := recover(); r != nil {
    // fmt.Println("recover", r)
    // }
    //}()

    //pod := `{"metadata":{"name":"python1-test-probe1-d4893279-1136-4eac-9808-98f7d0d541ff","namespace":"websocket","selfLink":"/api/v1/namespaces/websocket/pods/python-test-probe1-d4893279-1136-4eac-9808-98f7d0d541ff","uid":"d4893279-1136-4eac-9808-98f7d0d541ff","resourceVersion":"3903081","creationTimestamp":"2022-02-24T12:43:49Z"},"spec":{"volumes":[{"name":"localtime","hostPath":{"path":"/etc/localtime","type":""}},{"name":"ha-mailbox_container-0","hostPath":{"path":"/run/docker/ha-mailbox/container-0_python-test-probe1-d4893279-1136-4eac-9808-98f7d0d541ff","type":""}}],"containers":[{"name":"container-0","image":"fd.fusiondirector.huawei.com/library/pyhton-test:7.0","resources":{"limits":{"cpu":"1","memory":"512Mi"},"requests":{"cpu":"250m","memory":"512Mi"}},"volumeMounts":[{"name":"localtime","readOnly":true,"mountPath":"/etc/localtime"},{"name":"ha-mailbox_container-0","mountPath":"/var/local/ha-mailbox"}],"terminationMessagePath":"/dev/termination-log","terminationMessagePolicy":"File","imagePullPolicy":"IfNotPresent","securityContext":{"capabilities":{},"privileged":false}}],"restartPolicy":"Always","terminationGracePeriodSeconds":30,"dnsPolicy":"ClusterFirst","serviceAccountName":"default","serviceAccount":"default","hostNetwork":true,"securityContext":{},"imagePullSecrets":[{"name":"fusion-director-docker-registry-secret"}],"schedulerName":"default-scheduler","tolerations":[{"key":"node.kubernetes.io/unreachable","operator":"Exists","effect":"NoExecute"},{"key":"node.kubernetes.io/not-ready","operator":"Exists","effect":"NoExecute"},{"key":"node.kubernetes.io/network-unavailable","operator":"Exists","effect":"NoExecute"}]},"status":{}}`
    orm.RegisterModel(new(dao.User))
    dao.InitDBConfig("sqlite3", "default", "D:\\huawei-oj\\test\\work\\gwx.db")

    //userExtra := dao.UserExtra{
    // UserPhone: "123456",
    // UserQQ: "123",
    // UserCity: "123",
    //}

    user := dao.User{
    UserId: 1,
    UserName: "test",
    UserPwd: "123456",
    UserPhone: "123456",
    UserQQ: "123",
    UserCity: "123",
    }

    wg := sync.WaitGroup{}
    wg.Add(1)
    go func() {
    select {
    case <-time.After(2 * time.Second):
    fmt.Println("time is over")
    wg.Done()
    }
    }()
    // 数据库操作
    err := dao.InsertOrUpdate(&user)
    if err != nil {
    fmt.Println(err)
    }
    fmt.Println(err)
    fmt.Println("end do something")

    wg.Wait()

    }

    ```

  • 相关阅读:
    HTML5: HTML5 WebSocket
    mfs-管理员
    java实现平面点最小距离
    java实现平面点最小距离
    java实现平面点最小距离
    java实现排他平方数
    java实现排他平方数
    java实现排他平方数
    java实现排他平方数
    java实现排他平方数
  • 原文地址:https://www.cnblogs.com/gongxianjin/p/16512461.html
Copyright © 2020-2023  润新知