gorm访问SQLite

场景1:连接db并访问

# 创建数据库表
.open test.db
create table student(id int primary key not null, name char(10) not null, age int not null);

# 下载go依赖
go get gorm.io/gorm
go get gorm.io/driver/sqlite

 

package main

import (
	"fmt"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

type Student struct {
	Id   int    `gorm:"primary_key"`
	Name string `gorm:"column:name"`
	Age  int    `gorm:"column:age"`
}

func (Student) TableName() string {
	return "student"
}

func main() {
	db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
	if err != nil {
		fmt.Println("failed to connect database")
		return
	}
	fmt.Println("connect db ok")

	var count int64
	if err := db.Model(&Student{}).Count(&count).Error; err != nil {
		fmt.Printf("get count failed, err is %v", err)
		return
	}
	fmt.Printf("count is %d\n", count)
}

 问题1:database driver: unknown driver sqlite3

go install -tags 'sqlite3' github.com/golang-migrate/migrate/v4/cmd/migrate@latest

问题2:database is locked

SQLite不支持并发写入,通过加锁来串行写入。

问题3:如何延长慢SQL时间阈值和避免输出执行SQL错误日志

db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{
	Logger: logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             time.Second,   // Slow SQL threshold
			LogLevel:                  logger.Silent, // Log level
			IgnoreRecordNotFoundError: true,          // Ignore ErrRecordNotFound error for logger
			ParameterizedQueries:      true,          // Don't include params in the SQL log
			Colorful:                  false,         // Disable color
		},
	),
})

 

posted on 2024-12-14 00:35  王景迁  阅读(14)  评论(0编辑  收藏  举报

导航