如何在Golang中查询SQLite3数据库?

huangapple go评论84阅读模式
英文:

how to Query into sqlite3 in golang?

问题

我的表函数

func createTransactionTable(db *sql.DB) {
    transaction := `CREATE TABLE IF NOT EXISTS Transaction_history(
        "rollno" INTEGER UNSIGNED NOT NULL,
        "isReward" INTEGER UNSIGNED NOT NULL,
        "transfered_to" INTEGER UNSIGNED NOT NULL,
        "transfered_amount" INTEGER UNSIGNED NOT NULL,
        "redeems" INTEGER UNSIGNED NOT NULL,
        "date" TEXT NOT NULL
        );`
    statement, err := db.Prepare(transaction)
    if err != nil {
        panic(err)
    }
    statement.Exec()
    fmt.Println("trasaction table created")
}

查询函数

count, err := db.Exec(`SELECT count(isReward) from Transaction_history WHERE rollno = ? AND isReward = ?`, rollno, 1)
if err != nil {
    panic(err)
}
if count != 0 {
    return true
}
return false

我试图找到表中满足条件 isReward = 1 和指定 rollno 的行数,但是出现了问题,我不知道如何实现。我知道这是一个非常基本的问题,但是我已经搜索了很多,没有找到符合我的需求的解决方案,所以需要帮助。

英文:

My table function

func createTransactionTable(db *sql.DB) {
	transaction := `CREATE TABLE IF NOT EXISTS Transaction_history(
		"rollno" INTEGER UNSIGNED NOT NULL,
		"isReward" INTEGER UNSIGNED NOT NULL,
		"transfered_to" INTEGER UNSIGNED NOT NULL,
		"transfered_amount" INTEGER UNSIGNED NOT NULL,
		"redeems" INTEGER UNSIGNED NOT NULL,
		"date" TEXT NOT NULL
		);`
	statement, err := db.Prepare(transaction)
	if err != nil {
		panic(err)
	}
	statement.Exec()
	fmt.Println("trasaction  table created")
}

query function

count, err := db.Exec(`SELECT count(isReward) from Transaction_history WHERE rollno = ? AND isReward = ?`, rollno, 1)
if err != nil {
	panic(err)
}
if count != 0 {
	return true
}
return false

I am trying to find the no of rows of in my table where isReward = 1 and rollno is as specified of our choice but is giving and i dont know how to achieve, i know it is a very basic but literally searched but didn't get anything that will fit my need, so need help

答案1

得分: 1

文档中可以看到:

> Exec执行不返回行的查询。例如:插入和更新操作。

尝试使用Query代替。我没有对你的数据集进行测试(显然),但希望它能给你一些好的方向。此外,你应该正确处理错误。

type row struct {
	Count int `json:"count"`
}
response, _ := db.Query("SELECT count(isReward) as count from Transaction_history WHERE rollno = ? AND isReward = ?", rollno, 1)
var rows []row
_ = response.Scan(&rows)
count := rows[0].Count

如果你遇到数据库锁定错误,请确保不要同时查询SQLite。你可以创建一个全局互斥锁,并确保对数据库的每个查询都获取锁。

var m sync.Mutex

func createTransactionTable(...) {
	m.Lock()
	defer m.Unlock()
	// 在这里执行你的查询
}
英文:

From the docs:

> Exec executes a query that doesn't return rows. For example: an INSERT and UPDATE.

Try Query instead. I didn't test this against your dataset (obviously) but hopefully it gives you some good direction. Also you should properly handler errors.

type row struct {
	Count int `json:"count"`
}
response, _ := db.Query("SELECT count(isReward) as count from Transaction_history WHERE rollno = ? AND isReward = ?", rollno, 1)
var rows []row
_ = response.Scan(&rows)
count := rows[0].Count

If you're getting a database lock error, make sure you're not trying to query SQLite concurrently. You can create a global mutex, and make sure that every query against the database acquires the lock.

var m sync.Mutex

func createTransactionTable(...) {
	m.Lock()
	defer m.Unlock()
	// Perform your query here
}

答案2

得分: 0

我认为如果你使用像这样的驱动程序会更容易。

sqliteDatabase, _ := sql.Open("sqlite3", "./sqlite-database.db") // 打开已创建的 SQLite 文件
defer sqliteDatabase.Close() // 延迟关闭数据库
createTable(sqliteDatabase) // 创建数据库表

// 插入记录
insertStudent(sqliteDatabase, "0001", "Liana Kim", "Bachelor")

// 像这样的 InsertStudent 函数

createStudentTableSQL := `CREATE TABLE student (
	"idStudent" integer NOT NULL PRIMARY KEY AUTOINCREMENT,		
	"code" TEXT,
	"name" TEXT,
	"program" TEXT		
);` 

log.Println("创建 student 表...")
statement, err := db.Prepare(createStudentTableSQL) // 准备 SQL 语句
if err != nil {
	log.Fatal(err.Error())
}
statement.Exec() // 执行 SQL 语句
log.Println("student 表已创建")

你可以使用类似这样的方法。

英文:

I think it will be easier if you use Driver like this

sqliteDatabase, _ := sql.Open
    ("sqlite3", "./sqlite-database.db") // Open the created SQLite File
	defer sqliteDatabase.Close() // Defer Closing the database
	createTable(sqliteDatabase) // Create Database Tables

        // INSERT RECORDS
	insertStudent(sqliteDatabase, "0001", "Liana Kim", "Bachelor")

// and InsertStudent func like this

createStudentTableSQL := `CREATE TABLE student (
		"idStudent" integer NOT NULL PRIMARY KEY AUTOINCREMENT,		
		"code" TEXT,
		"name" TEXT,
		"program" TEXT		
	  );` 

	log.Println("Create student table...")
	statement, err := db.Prepare(createStudentTableSQL) // Prepare SQL Statement
	if err != nil {
		log.Fatal(err.Error())
	}
	statement.Exec() // Execute SQL Statements
	log.Println("student table created")

You can use methods like this

huangapple
  • 本文由 发表于 2021年6月28日 23:46:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/68166341.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定