sqlite - how do I get a one row result back? (luaSQLite3)

陌路散爱 提交于 2019-12-05 18:25:45

Here is a demo of getting the returned count:

> require "lsqlite3"
> db = sqlite3.open":memory:"
> db:exec "create table foo (x,y,z);"
> for x in db:urows "select count(*) from foo" do print(x) end
0
> db:exec "insert into foo values (10,11,12);"
> for x in db:urows "select count(*) from foo" do print(x) end
1
> 

In order to get a single row use the db:first_row method. Like so.

row = db:first_row("SELECT `id` FROM `table`")
print(row.id)

In order to get the row count use the SQL COUNT statement. Like so.

row = db:first_row("SELECT COUNT(`id`) AS count FROM `table`")
print(row.count)

EDIT: Ah, sorry for that. Here are some methods that should work.

You can also use db:nrows. Like so.

rows = db:nrows("SELECT `id` FROM `table`")
row = rows[1]
print(row.id)

We can also modify this to get the number of rows.

rows = db:nrows("SELECT COUNT(`id`) AS count FROM `table`")
row = rows[1]
print(row.count)

Just loop over the iterator you get back from the rows or whichever function you use. Except you put a break at the end, so you only iterate once.

Getting the count is all about using SQL. You compute it with the SELECT statement:

SELECT count(*) FROM ...

This will return one row containing a single value: the number of rows in the query.

This is similar to what I'm using in my project and works well for me.

local query = "SELECT content FROM playerData WHERE name = 'myTable' LIMIT 1"

local queryResultTable = {}

local queryFunction = function(userData, numberOfColumns, columnValues, columnTitles)

    for i = 1, numberOfColumns do

        queryResultTable[columnTitles[i]] = columnValues[i]

    end

end

db:exec(query, queryFunction)

for k,v in pairs(queryResultTable) do

    print(k,v)

end

You can even concatenate values into the query to place inside a generic method/function.

local query = "SELECT * FROM ZQuestionTable WHERE ConceptNumber = "..conceptNumber.." AND QuestionNumber = "..questionNumber.." LIMIT 1"
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!