草庐IT

sqlite - 去编程: sqlite_master returns EOF using sqlite3 package

coder 2024-07-12 原文

我试图在表创建后检查表是否存在,但是 "SELECT name FROM sqlite_master WHERE type='table' AND name='testtable';" 什么都不返回(EOF)。我做错了什么?

Sqlite3 包取自http://code.google.com/p/go-sqlite/source/browse/#hg%2Fgo1%2Fsqlite3 去版本:1.2.1

得到:

hello, world
FileExists(dbname) returned: false
database ok
creating testtable...
success!
inserting something...
checking testtable...
Failed to scan variable, error: EOF

预期:

hello, world
FileExists(dbname) returned: false
database ok
creating testtable...
success!
inserting something...
checking testtable...
Table detected

代码:

package main
import "os"
import "fmt"
import "time"
import "code.google.com/p/go-sqlite/go1/sqlite3"
func main() {
dbname := "sqlite.db"
defer time.Sleep(5000 * time.Millisecond)
fmt.Printf("hello, world\n")
os.Remove(dbname)
fe := FileExists(dbname)
fmt.Printf("FileExists(dbname) returned: %t\n", fe) 
db, err := sqlite3.Open(dbname)
defer db.Close()
if err != nil {
    fmt.Printf("failed to open database, error: " + err.Error() + "\n") 
    return
}
fmt.Printf("database ok\n")
if fe != true {
    fmt.Printf("creating testtable...\n") 
    err = db.Exec("CREATE TABLE testtable (id INTEGER PRIMARY KEY AUTOINCREMENT, text VARCHAR(200));")
    if err != nil {
        fmt.Printf("error: " + err.Error() + "\n") 
        return
    } else {
        fmt.Printf("success!\n") 
    }
    fmt.Printf("inserting something...\n") 
    insertSql := `INSERT INTO testtable(text) VALUES("This is some random text to test it");`
    err = db.Exec(insertSql)
    if err != nil {
        fmt.Printf("Error while Inserting: " + err.Error() + "\n")
        return
    }
    fmt.Printf("checking testtable...\n") 
    CheckTable, err := db.Prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='testtable';")
    err = CheckTable.Exec()
    if err != nil {
        fmt.Printf("failed to check table, error: " + err.Error() + "\n")
        return
    }
    var tablename string
    //Same result removing '//'
    //requeststatus := CheckTable.Next() 
        err = CheckTable.Scan(&tablename)
        if err != nil {
            fmt.Printf("Failed to scan variable, error: " + err.Error() + "\n")
            return
        }
    if tablename != "testtable" {
        fmt.Printf("No table detected\n")
    } else {
    fmt.Printf("Table detected\n")
    }
}
}


func FileExists(fn string) bool {
if _, err := os.Stat(fn); err == nil {
    return true
} else {
    return false
}
}

最佳答案

Stmt.Exec documentation说:

No rows are returned.

要返回数据,请使用 Query相反。

关于sqlite - 去编程: sqlite_master returns EOF using sqlite3 package,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22879291/

有关sqlite - 去编程: sqlite_master returns EOF using sqlite3 package的更多相关文章

随机推荐