如何在 Julia sqlite 库中绑定参数?

How do you bind parameters in the Julia sqlite library?

我正在尝试使用 Julia SQLite.jl 库,但我不知道如何绑定变量。

using SQLite

# Create DB and table
db = SQLite.DB("mydb.sqlite")
SQLite.createtable!(db, "Student", Tables.Schema((:Name, :Grade), (String, Int64)); temp=false, ifnotexists=true)

# Add vals
SQLite.execute(db, "INSERT INTO Student VALUES('Harry', 1)")

# Prepared statement: Can use: ?, ?NNN, :AAA, $AAA, @AAA

insert_stmt = SQLite.Stmt(db, "INSERT INTO Student VALUES(:N, :G)")
SQLite.bind!(insert_stmt, Dict("N"=>"George", "G"=>"4"))
# This fails, with error:  SQLiteException("`:N` not found in values keyword arguments to bind to sql statement")

insert_stmt = SQLite.Stmt(db, "INSERT INTO Student VALUES(:N, :G)")
SQLite.bind!(insert_stmt, Dict(:N=>"George", :G=>"4"))
SQLite.execute(insert_stmt)
# This fails, with error:  SQLiteException("values should be provided for all query placeholders")

insert_stmt = SQLite.Stmt(db, "INSERT INTO Student VALUES(?1, ?2)")
SQLite.bind!(insert_stmt, ["George", "4"])
SQLite.execute(insert_stmt)
# This fails, with error: SQLiteException("values should be provided for all query placeholders")

insert_stmt = SQLite.Stmt(db, "INSERT INTO Student VALUES(':N', ':G')")
SQLite.bind!(insert_stmt, Dict(:N=>"George", :G=>"4"))
SQLite.execute(insert_stmt) 
# This doesn't bind, it inserts ':N' and ':G'

正确的语法是什么?谢谢!

你可以试试:

stmt = SQLite.Stmt(db, "INSERT INTO Student VALUES(?, ?)")
DBInterface.execute(stmt, ["Jack",2])

让我们看看这是否有效:

julia> DBInterface.execute(db, "SELECT * FROM Student") |> DataFrame
2×2 DataFrame
 Row │ Name    Grade
     │ String  Int64
─────┼───────────────
   1 │ Harry       1
   2 │ Jack        2

(类似于 Przemyslaw Szufel 的回答,只是使用问题中的命名参数。)

DBInterface.execute 的文档(建议使用 SQLite.execute 的文档)说:

DBInterface.execute(db::SQLite.DB, sql::String, [params]) DBInterface.execute(stmt::SQLite.Stmt, [params])

Bind any positional (params as Vector or Tuple) or named (params as NamedTuple or Dict) parameters to an SQL statement, given by db and sql or as an already prepared statement stmt, execute the query and return an iterator of result rows.

所以你可以传递你的Dict直接执行为:

julia> insert_stmt = SQLite.Stmt(db, "INSERT INTO Student VALUES(:N, :G)")
julia> DBInterface.execute(insert_stmt, Dict(:N => "Palani", :G => 3))
SQLite.Query(SQLite.Stmt(SQLite.DB("mydb.sqlite"), 1), Base.RefValue{Int32}(101), Symbol[], Type[], Dict{Symbol, Int64}(), Base.RefValue{Int64}(0))