【问题标题】:how to Query into sqlite3 in golang?如何在golang中查询到sqlite3?
【发布时间】:2026-01-30 02:25:01
【问题描述】:

我的表格功能

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 的行数,这是我们选择的指定但正在给予,我不知道如何实现,我知道这是一个非常基本但字面上搜索但没有得到任何满足我需要的东西,所以需要帮助

【问题讨论】:

  • 我不明白这个问题很清楚我在问什么,仍然是人们而不是帮助不喜欢你的问题

标签: sqlite go


【解决方案1】:

来自docs

Exec 执行不返回行的查询。例如:INSERT 和 UPDATE。

改用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()
    // Perform your query here
}

【讨论】:

  • 我也面临数据库锁定错误,我已经搜索过互斥锁可以解决这个问题,你喜欢我如何应用互斥锁
  • 查看thisthis。另请参阅上面的更新答案。
【解决方案2】:

我认为如果你使用像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")

你可以使用这样的方法

【讨论】: