英文:
How to delete row in go-sqlite3
问题
我正在使用以下代码向表中添加两行:
package main
import (
"database/sql"
"fmt"
"log"
"strconv"
_ "github.com/mattn/go-sqlite3"
)
func main() {
database, _ := sql.Open("sqlite3", "./nraboy.db")
statement, _ := database.Prepare("CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY, firstname TEXT, lastname TEXT)")
statement.Exec()
statement, _ = database.Prepare("INSERT INTO people (firstname, lastname) VALUES (?, ?)")
statement.Exec("Nic", "Raboy")
statement, _ = database.Prepare("INSERT INTO people (firstname, lastname) VALUES (?, ?)")
statement.Exec("Tom", "Hardy")
_, err := statement.Exec("delete from people where id = 1")
if err != nil {
log.Fatal(err)
}
rows, _ := database.Query("SELECT id, firstname, lastname FROM people")
var id int
var firstname string
var lastname string
for rows.Next() {
rows.Scan(&id, &firstname, &lastname)
fmt.Println(strconv.Itoa(id) + ": " + firstname + " " + lastname)
}
}
但是当我添加 _, err := statement.Exec("delete from people where id = 1")
来删除一行时,我得到以下错误:
2021/07/09 16:21:07 sql: expected 2 arguments, got 1
exit status 1
如何删除表中的行?
英文:
I'm using below code for adding two rows in table
package main
import (
"database/sql"
"fmt"
"log"
"strconv"
_ "github.com/mattn/go-sqlite3"
)
func main() {
database, _ := sql.Open("sqlite3", "./nraboy.db")
statement, _ := database.Prepare("CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY, firstname TEXT, lastname TEXT)")
statement.Exec()
statement, _ = database.Prepare("INSERT INTO people (firstname, lastname) VALUES (?, ?)")
statement.Exec("Nic", "Raboy")
statement, _ = database.Prepare("INSERT INTO people (firstname, lastname) VALUES (?, ?)")
statement.Exec("Tom", "Hardy")
_, err := statement.Exec("delete from people where id = 1")
if err != nil {
log.Fatal(err)
}
rows, _ := database.Query("SELECT id, firstname, lastname FROM people")
var id int
var firstname string
var lastname string
for rows.Next() {
rows.Scan(&id, &firstname, &lastname)
fmt.Println(strconv.Itoa(id) + ": " + firstname + " " + lastname)
}
}
but when I'm adding _, err := statement.Exec("delete from people where id = 1")
for removing one of row I get following error:
2021/07/09 16:21:07 sql: expected 2 arguments, got 1
exit status 1
How to delete row in table ?
答案1
得分: 1
看起来你忘记调用statement, _ = database.Prepare("delete from people where id = 1")
来执行删除命令了。当你调用statement.Exec("delete from people where id = 1")
时,之前准备的语句仍然有效,并且它期望两个参数(firstname和lastname)。
英文:
It looks like you forgot to call statement, _ = database.Prepare("delete from people where id = 1")
for the delete command. When you are calling statement.Exec("delete from people where id = 1")
the statement that was previously prepared is still in effect, and it expects two arguments (firstname, lastname).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论