beego-orm-sqlite
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()
}
```
beego-orm-sqlite的更多相关文章
- beego orm 忽略字段
忽略字段 设置 - 即可忽略 struct 中的字段 type User struct { ... AnyField string `orm:"-"` ... } beego or ...
- golang学习笔记16 beego orm 数据库操作
golang学习笔记16 beego orm 数据库操作 beego ORM 是一个强大的 Go 语言 ORM 框架.她的灵感主要来自 Django ORM 和 SQLAlchemy. 目前该框架仍处 ...
- 基于beego orm 针对oracle定制
目前golang的ORM对oracle支持都没有mysql那样完整,一个orm要同时兼容mysql和oracle由于在sql语法上区别,会使整orm变的非常臃肿. 本项目是在beego orm上修改, ...
- Golang beego ORM + CRUP 操作详解
构建beego Web 项目 首先构建一个beego 的web 项目,这个我们完全可以参考beego 官网中的开发文档,上面介绍的非常的详细,在这我就不给大家介绍,主要是介绍ORM ...
- beego orm操作mysql数据库
慢慢弄起来~~ 按官方操作文档试一下. 那个err重复和user编号问题,以后再弄.. package main import ( "fmt" "github.com/a ...
- beego orm mysql
beego框架中的rom支持mysql 项目中使用到mvc模式,总结下使用方式: models中 package models import ( //使用beego orm 必备 "gith ...
- beego——ORM使用方法
先来看一个简单示例: models.gp package main import ( "github.com/astaxie/beego/orm" ) type User stru ...
- beego orm
http://beego.me/docs/mvc/model/overview.md go get github.com/astaxie/beego/orm Simple Usage package ...
- beego框架学习--beego orm映射
什么是ORM 即Object-Relationl Mapping,它的作用是在关系型数据库和对象之间作一个映射,这样,我们在具体的操作数据库的时候,就不需要再去和复杂的SQL语句打交道,只要像平时操作 ...
- beego orm的使用
在使用beego model 去操作数据库时 有一些疑惑 找到了一个比较好的博文 原文地址 : https://my.oschina.net/u/252343/blog/829912 (Kelvin ...
随机推荐
- Linux软件包常见的几种下载、安装方法
在线源下载和安装 如果服务器是处于在线状态,在使用默认下载源是外国的情况下,安装更新软件包往往会比较痛苦的存在,下载了许久来一个超时就gg了.国内有许多镜像源,完美的解决了这个问题. 对于rpm系列的 ...
- Linux虚拟机 RHEL8.0安装步骤
一. 创建空白虚拟机 1.打开 VMware 虚拟机软件依次选择新建虚拟机并选择选择"自定义" 自定义功能更加全面,典型就是比较简单的配置 2.选择对应的 VMware 版本,此则 ...
- KingbaseES V8R3 由于修改系统时间导致sys_rman备份故障案例
案例说明: 此案例,为复现"current time may be rewound"错误.对于数据库环境,在使用前必须保证系统时间的正确性.如果数据库创建后,再将系统时间修改为 ...
- 聊聊 asp.net core 认证和授权
使用asp.net core 开发应用系统过程中,基本上都会涉及到用户身份的认证,及授权访问控制,因此了解认证和授权流程也相当重要,下面通过分析asp.net core 框架中的认证和授权的源码来分析 ...
- C 语言 struct 第一个成员变量的妙用
一.双重身份 如下定义了一个 School 结构体: typedef struct School { int a; int b; }SCHOOL_S; SCHOOL_S stSch; 下面我们来输出一 ...
- ProxySQL 配置ProxySQL
转载自:https://www.jianshu.com/p/212397a1be67 假定你已经对ProxySQL的架构有所了解.本文对ProxySQL的所有配置都是使用Admin管理接口完成的,该管 ...
- 安装skywalking(测试使用)
官方下载地址:https://skywalking.apache.org/downloads/ 需要: JDK8到JDK12已测试,其他版本未测试. # 在线安装jdk8 rpm -ivh https ...
- shell分割字符串并赋值给变量
假如变量var的值为:num=12,也即var="num=12",现在想把 12赋值给变量id awk 的-F 后跟上要分割字符串时的指定分隔符 awk中$0是要分割的字符串,$1 ...
- 使用logstash同步mysql 多表数据到ElasticSearch实践
参考样式即可,具体使用配置参数根据实际情况而定 input { jdbc { jdbc_connection_string => "jdbc:mysql://localhost/数据库 ...
- MySQL集群搭建(4)-MMM+LVS+Keepalived
1 LVS 介绍 1.1 简介 LVS 是 Linux Virtual Server 的简写,意即 Linux 虚拟服务器,是一个虚拟的服务器集群系统.本项目在 1998 年 5 月由章文嵩博士成立, ...