Commonly used libraries in golang - operating sqlite database

1. sqlite

SQLite is an open source embedded relational database that implements a self-sufficient, serverless, configuration-free, transactional SQL database engine. It is a zero-configuration database, which means that unlike other database systems such as MySQL, PostgreSQL, etc., SQLite does not require a separate service to be set up and managed in the system. This also makes SQLite a very lightweight database solution, very suitable for small projects, embedded databases or test environments.

Some of the key features of SQLite include:

  • Serverless: SQLite is not a separate service process but is embedded directly into the application. It reads and writes disk files directly.
  • Transactional: SQLite support
  • ACID (Atomicity, Consistency, Isolation, Durability) properties ensure that all transactions are safe and consistent, even in the event of a system crash or power outage.
  • Zero-configuration: SQLite does not require any configuration or administration, which makes it very easy to install and use.
  • Self-contained: SQLite is a self-contained system, which means that it hardly depends on any other external systems or libraries, which makes cross-platform porting of SQLite very convenient.
  • Small: SQLite is very small and lightweight, and the full-featured SQLite database engine is only a few hundred KB in size.
  • Widely used: SQLite is widely used in a variety of products and systems, including mobile phones, tablets, embedded systems, Internet of Things devices, etc. It is also widely used in website development, scientific research, data analysis and other fields.

In some lightweight application scenarios, SQLite is an ideal choice because it is simple, efficient, easy to use and deploy. However, for application scenarios that need to handle a large number of concurrent write operations or require more advanced functions (such as user management or stored procedures, etc.), a more full-featured database system (such as PostgreSQL or MySQL) may be a better choice.

Use the sqlite3 command line tool to create a database and query data

sudo apt install sqlite3
sqlite3 --version

Run the following command to start the sqlite3 tool and specify the name of the database file to create (for example, mydatabase.db):

sqlite3 sqlite.db

At the sqlite3 prompt, enter the .tables command to list all tables in the database:

.tables
SELECT * FROM notifications;

Exit the command line environment:.quit /.exit

2. About mattn/go-sqlite3

github: https://github.com/mattn/go-sqlite3
Official documentation: https://pkg.go.dev/github.com/mattn/go- sqlite3?utm_source=godoc

github.com/mattn/go-sqlite3: This is a popular SQLite3 driver that supports most features of SQLite. It is a binding for the official SQLite C library and is widely used and has many users.

3. Use of mattn/go-sqlite3

To compile this package on Linux, you must install the development tools for your linux distribution.
Ubuntu

sudo apt-get install build-essential
package main

import (
	"database/sql"
	"fmt"
	"log"

	_ "github.com/mattn/go-sqlite3"
)

func main() {
    
    
	// 打开数据库连接
	db, err := sql.Open("sqlite3", "test.db")
	if err != nil {
    
    
		log.Fatal(err)
	}
	defer db.Close()

	// 创建表和清空表数据
	_, err = db.Exec(`
		CREATE TABLE IF NOT EXISTS foo (
			id INTEGER PRIMARY KEY,
			name TEXT
		);
		DELETE FROM foo;
	`)
	if err != nil {
    
    
		log.Fatal(err)
	}

	// 开启事务
	tx, err := db.Begin()
	if err != nil {
    
    
		log.Fatal(err)
	}
	defer tx.Rollback() // 注意:如果出现错误,及时回滚事务

	// 准备插入语句
	stmt, err := tx.Prepare("INSERT INTO foo(id, name) VALUES(?, ?)")
	if err != nil {
    
    
		log.Fatal(err)
	}
	defer stmt.Close()

	// 执行插入操作
	for i := 0; i < 100; i++ {
    
    
		_, err = stmt.Exec(i, fmt.Sprintf("こんにちわ世界%03d", i))
		if err != nil {
    
    
			log.Fatal(err)
		}
	}

	// 提交事务
	err = tx.Commit()
	if err != nil {
    
    
		log.Fatal(err)
	}

	// 查询数据并打印
	rows, err := db.Query("SELECT id, name FROM foo")
	if err != nil {
    
    
		log.Fatal(err)
	}
	defer rows.Close()
	for rows.Next() {
    
    
		var id int
		var name string
		err = rows.Scan(&id, &name)
		if err != nil {
    
    
			log.Fatal(err)
		}
		log.Println(id, name)
	}
	err = rows.Err()
	if err != nil {
    
    
		log.Fatal(err)
	}
}

4. Summary of common problems when using sqlite in go

Compilation error under window: Binary was compiled with ‘CGO_ENABLED=0’, go-sqlite3 require

s cgo to work. This is a stub

go-sqlite3 requires CGO to work properly.

The solution is to set the environment variable CGO_ENABLED=1 to enable cgo during compilation.

Error when compiling under window: cgo: C compiler “gcc” not found: exec: “gcc”: executable file not found in %PATH%

Compiling with CGO requires a C compiler. On Windows systems, the C compiler is installed to support the CGO compilation process.

CGO is a feature of the Go language that allows calling C language code from Go code. In order to support such cross-language calls, CGO needs to rely on a C compiler to compile and link C code.

On Windows, common C compilers include MinGW-w64, TDM-GCC, etc. After installing one of the C compilers, add the path to its executable file to your system's PATH environment variable so that the Go language can find and use the C compiler for CGO compilation.

So, if you need to compile Go code using CGO on Windows, make sure you have the C compiler installed and add its path to your system's PATH environment variable.

There are also instructions in the official readme:
https://github.com/mattn/go-sqlite3#linux

The official recommendation is TDM-GCC.

TDM-GCC and MinGW-w64 are both commonly used C/C++ compiler suites in Windows environments to support CGO compilation.

TDM-GCC:
TDM-GCC is a fork based on MinGW that provides a set of precompiled Windows versions of the GCC toolchain.
TDM-GCC is relatively easy to install and configure, and is suitable for entry-level users.
TDM-GCC provides better compatibility and stability, as well as better support and maintenance.

Summary: TDM-GCC is a good choice for most users because it is easy to install and use, and provides a stable Windows version of the GCC toolchain.

报错:sql: unknown driver “sqlite3” (forgotten import?)

Caused by forgetting to import the "github.com/mattn/go-sqlite3" package.

In your code, make sure to import the "github.com/mattn/go-sqlite3" package before using the SQLite driver by adding the following import statement:

import _ "github.com/mattn/go-sqlite3"

This will ensure that the SQLite driver is properly registered and will enable you to use the "sqlite3" driver name in your code.

Guess you like

Origin blog.csdn.net/inthat/article/details/134726254