Golang(Go语言)GORM使用SQLite数据库
以下是GORM使用标准未加密的SQLite数据库方法(由https://gorm.io/docs/提供)
1、安装引用
go get -u gorm.io/gorm
go get -u gorm.io/driver/sqlite
2、开始享用
package main import ( "gorm.io/gorm" "gorm.io/driver/sqlite" ) type Product struct { gorm.Model Code string Price uint } func main() { db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { panic("failed to connect database") } // Migrate the schema db.AutoMigrate(&Product{}) // Create db.Create(&Product{Code: "D42", Price: 100}) // Read var product Product db.First(&product, 1) // find product with integer primary key db.First(&product, "code = ?", "D42") // find product with code D42 // Update - update product's price to 200 db.Model(&product).Update("Price", 200) // Update - update multiple fields db.Model(&product).Updates(Product{Price: 200, Code: "F42"}) // non-zero fields db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"}) // Delete - delete product db.Delete(&product, 1) }
以下是GORM使用加密的SQLite数据库方法
1、安装引用
go get -u gorm.io/gorm go get -u github.com/jackfr0st13/gorm-sqlite-cipher
2、开始享用
package main import ( sqliteEncrypt "github.com/jackfr0st13/gorm-sqlite-cipher" "gorm.io/gorm" ) type Product struct { gorm.Model Code string Price uint } func main() { //设置密码 dsn := fmt.Sprintf("test.db?_pragma_key=%s&_pragma_cipher_page_size=4096", "password") db, err := gorm.Open(sqliteEncrypt.Open(dsn), &gorm.Config{}) if err != nil { panic("failed to connect database") } // Migrate the schema db.AutoMigrate(&Product{}) // Create db.Create(&Product{Code: "D42", Price: 100}) // Read var product Product db.First(&product, 1) // find product with integer primary key db.First(&product, "code = ?", "D42") // find product with code D42 // Update - update product's price to 200 db.Model(&product).Update("Price", 200) // Update - update multiple fields db.Model(&product).Updates(Product{Price: 200, Code: "F42"}) // non-zero fields db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"}) // Delete - delete product db.Delete(&product, 1) }
可以看到只是在未加密数据库使用代码的基础之上做了些许修改就支持加密了,GURD部分不需要任何变动,具体修改如下:
"gorm.io/driver/sqlite"
改为
sqliteEncrypt "github.com/jackfr0st13/gorm-sqlite-cipher"
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
改为 dsn := fmt.Sprintf("test.db?_pragma_key=%s&_pragma_cipher_page_size=4096", "password") db, err := gorm.Open(sqliteEncrypt.Open(dsn), &gorm.Config{})