当前位置: 首页 > 工具软件 > c2sqlite > 使用案例 >

Go语言sqlite数据库增删改查

宗政博文
2023-12-01

命令行sqlite增删改查

创建数据库文件

# 如果没有创建sqlite数据库
curtis@curtis-Aspire-E5-471G:~/go_env/sqlite$ sqlite3
SQLite version 3.40.0 2022-11-16 12:10:08
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> .open data.db3

# 如果已经创建sqlite数据库,直接打开
curtis@curtis-Aspire-E5-471G:~/go_env/sqlite$ sqlite3 data.db3
SQLite version 3.40.0 2022-11-16 12:10:08
Enter ".help" for usage hints.
sqlite> 

帮助命令信息查看

urtis@curtis-Aspire-E5-471G:~/go_env/sqlite$ sqlite3 data.db3
SQLite version 3.40.0 2022-11-16 12:10:08
Enter ".help" for usage hints.
sqlite> .help
.archive ...             Manage SQL archives
.auth ON|OFF             Show authorizer callbacks
.backup ?DB? FILE        Backup DB (default "main") to FILE
.bail on|off             Stop after hitting an error.  Default OFF
.binary on|off           Turn binary output on or off.  Default OFF
.cd DIRECTORY            Change the working directory to DIRECTORY
.changes on|off          Show number of rows changed by SQL
.check GLOB              Fail if output since .testcase does not match
.clone NEWDB             Clone data into NEWDB from the existing database
.connection [close] [#]  Open or close an auxiliary database connection
.databases               List names and files of attached databases
.dbconfig ?op? ?val?     List or change sqlite3_db_config() options
.dbinfo ?DB?             Show status information about the database
.dump ?OBJECTS?          Render database content as SQL
.echo on|off             Turn command echo on or off
.eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN
.excel                   Display the output of next command in spreadsheet
.exit ?CODE?             Exit this program with return-code CODE
.expert                  EXPERIMENTAL. Suggest indexes for queries
.explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto
.filectrl CMD ...        Run various sqlite3_file_control() operations
.fullschema ?--indent?   Show schema and the content of sqlite_stat tables
.headers on|off          Turn display of headers on or off
.help ?-all? ?PATTERN?   Show help text for PATTERN
.import FILE TABLE       Import data from FILE into TABLE
.imposter INDEX TABLE    Create imposter table TABLE on index INDEX
.indexes ?TABLE?         Show names of indexes
.limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT
.lint OPTIONS            Report potential schema issues.
.load FILE ?ENTRY?       Load an extension library
.log FILE|off            Turn logging on or off.  FILE can be stderr/stdout
.mode MODE ?OPTIONS?     Set output mode
.nonce STRING            Suspend safe mode for one command if nonce matches
.nullvalue STRING        Use STRING in place of NULL values
.once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE
.open ?OPTIONS? ?FILE?   Close existing database and reopen FILE
.output ?FILE?           Send output to FILE or stdout if FILE is omitted
.parameter CMD ...       Manage SQL parameter bindings
.print STRING...         Print literal STRING
.progress N              Invoke progress handler after every N opcodes
.prompt MAIN CONTINUE    Replace the standard prompts
.quit                    Exit this program
.read FILE               Read input from FILE or command output
.recover                 Recover as much data as possible from corrupt db.
.restore ?DB? FILE       Restore content of DB (default "main") from FILE
.save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)
.scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off
.schema ?PATTERN?        Show the CREATE statements matching PATTERN
.selftest ?OPTIONS?      Run tests defined in the SELFTEST table
.separator COL ?ROW?     Change the column and row separators
.session ?NAME? CMD ...  Create or control sessions
.sha3sum ...             Compute a SHA3 hash of database content
.shell CMD ARGS...       Run CMD ARGS... in a system shell
.show                    Show the current values for various settings
.stats ?ARG?             Show stats or turn stats on or off
.system CMD ARGS...      Run CMD ARGS... in a system shell
.tables ?TABLE?          List names of tables matching LIKE pattern TABLE
.testcase NAME           Begin redirecting output to 'testcase-out.txt'
.testctrl CMD ...        Run various sqlite3_test_control() operations
.timeout MS              Try opening locked tables for MS milliseconds
.timer on|off            Turn SQL timer on or off
.trace ?OPTIONS?         Output each SQL statement as it is run
.vfsinfo ?AUX?           Information about the top-level VFS
.vfslist                 List all available VFSes
.vfsname ?AUX?           Print the name of the VFS stack
.width NUM1 NUM2 ...     Set minimum column widths for columnar output
sqlite> 

获取当前终端表项显示相关信息

sqlite> .show
        echo: off
         eqp: off
     explain: auto
     headers: off
        mode: list
   nullvalue: ""
      output: stdout
colseparator: "|"
rowseparator: "\n"
       stats: off
       width: 
    filename: data.db3

创建一个表项,此时表项内容为空。

sqlite> .tables
sqlite> 
sqlite> CREATE TABLE IF NOT EXISTS "users" (
   ...> "id" integer primary key autoincrement,
   ...> "username" text not null,
   ...> "age" integer not null,
   ...> "job" text,
   ...> "hobby" text);
sqlite> .tables
users

往表项中添加数据并查看表项中所有数据,注意表项内容为字符串类型,需要用双引号。

sqlite> insert into users (username, age, job, hobby) values("curtis",100,"fox","river");
sqlite> SELECT * from users;
1|curtis|100|fox|river
sqlite> .headers on
sqlite> SELECT * from users;
id|username|age|job|hobby
1|curtis|100|fox|river

删除表项中的某条数据

sqlite> insert into users (username, age, job, hobby) values("xiaoli",100,"changjing","river");
sqlite> SELECT * from users;
id|username|age|job|hobby
1|curtis|100|fox|river
2|xiaoli|100|changjing|river
sqlite> delete from users where id=2;
sqlite> SELECT * from users;
id|username|age|job|hobby
1|curtis|100|fox|river

修改(更新)表项中的某条数据,如果需要更新多个字段,更新字段用逗号隔开即可,如果要多个符合条件的条目用and连接

sqlite> SELECT * from users;
id|username|age|job|hobby
1|curtis|100|fox|river
sqlite> update users set username="xiaoli" where age=100;
sqlite> SELECT * from users;
id|username|age|job|hobby
1|xiaoli|100|fox|river

修改数据打印的类型,默认为list,修改为表格

sqlite> .show
        echo: off
         eqp: off
     explain: auto
     headers: on
        mode: list
   nullvalue: ""
      output: stdout
colseparator: "|"
rowseparator: "\n"
       stats: off
       width: 
    filename: data.db3
sqlite> .mode colum
sqlite> .show
        echo: off
         eqp: off
     explain: auto
     headers: on
        mode: column --wrap 60 --wordwrap off --noquote
   nullvalue: ""
      output: stdout
colseparator: "|"
rowseparator: "\n"
       stats: off
       width: 
    filename: data.db3
sqlite> SELECT * from users;
id  username  age  job  hobby
--  --------  ---  ---  -----
1   xiaoli    100  fox  river

创建索引,在不读取整个表的情况下,索引使数据库应用程序可以更快地查找数据。

sqlite> CREATE INDEX index_age ON users (age);
sqlite> .indices users
index_age

查看某张表中的所有索引

sqlite> .indices table_name

查询数据库中所有表项

# 获取表项数量
select count(*)  from sqlite_master where type='table'

# 获取所有表项的名称
select name from sqlite_master where type = 'table'

go语言 sqlite数据库增删改查,利用一个github上一个开源的库,以上命令行相关操作均可用Go语言,但是

package main

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

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

const (
	dbDriverName = "sqlite3"
	dbName       = "./data.db3"
)

type user struct {
	Username string
	Age      int
	Job      string
	Hobby    string
}

func main() {
	db, err := sql.Open(dbDriverName, dbName)
	if checkErr(err) {
		return
	}

	// err = createTable(db)
	// if checkErr(err) {
	// 	return
	// }

	// err = insertData(db, user{"zhangsan", 28, "engineer", "play football"})
	// if checkErr(err) {
	// 	return
	// }

	res, err := queryData(db, "zhangsan")
	if checkErr(err) {
		return
	}

	fmt.Println(len(res))
	for _, val := range res {
		fmt.Println(val)
	}

	modifyData(db)

	res, err = queryData(db, "zhangsan")
	if checkErr(err) {
		return
	}

	fmt.Println(len(res))
	for _, val := range res {
		fmt.Println(val)
	}

	// r, err := delByID(db, 1)
	// if checkErr(err) {
	// 	return
	// }
	// if r {
	// 	fmt.Println("delete row success")
	// }
}

func createTable(db *sql.DB) error {
	sql := `create table if not exists "users" (
		"id" integer primary key autoincrement,
		"username" text not null,
		"age" integer not null,
		"job" text,
		"hobby" text
	)`
	_, err := db.Exec(sql)
	return err
}

func insertData(db *sql.DB, u user) error {
	sql := `insert into users (username, age, job, hobby) values(?,?,?,?)`
	stmt, err := db.Prepare(sql)
	if err != nil {
		return err
	}
	_, err = stmt.Exec(u.Username, u.Age, u.Job, u.Hobby)
	return err
}

func queryData(db *sql.DB, name string) (l []user, e error) {
	sql := `select * from users`
	stmt, err := db.Prepare(sql)
	if err != nil {
		return nil, err
	}
	rows, err := stmt.Query()
	if err != nil {
		return nil, err
	}
	var result = make([]user, 0)
	for rows.Next() {
		var username, job, hobby string
		var age, id int
		rows.Scan(&id, &username, &age, &job, &hobby)
		result = append(result, user{username, age, job, hobby})
	}
	return result, nil
}

func modifyData(db *sql.DB) {
	stmt, err := db.Prepare("update users set username=? where age=?")
	if stmt == nil || err != nil {
		panic(err)
	}
	_, err = stmt.Exec("xiaolizi", 28)
	if err != nil {
		panic(err)
	}
}

func delByID(db *sql.DB, id int) (bool, error) {
	sql := `delete from users where id=?`
	stmt, err := db.Prepare(sql)
	if err != nil {
		return false, err
	}
	res, err := stmt.Exec(id)
	if err != nil {
		return false, err
	}
	_, err = res.RowsAffected()
	if err != nil {
		return false, err
	}
	return true, nil
}

func checkErr(e error) bool {
	if e != nil {
		log.Fatal(e)
		return true
	}
	return false
}

func getTables(db *sql.DB) {
	var tableName string
	rows, err := db.Query(select name from sqlite_master where type = 'table')

	if err != nil {
		panic(err)
	}

	if rows.Next() {
			err = rows.Scan(&tableName)
			if err != nil {
				panic(err)
			}
			fmt.Println(tableName)
	}
}

参考链接:https://www.jianshu.com/p/c2f72fc0bdb5,在这个基础上添加添加修方法,获取表项的方法。

sqlite3数据库模糊查询

> select * from fault where time LIKE "20201216%"
 类似资料: