Luasql (Sqlite3) accepting only a "value"

1

I'm trying to create a simple table, just with names, but when I enter a value, you can not enter any more. How I am doing:

require 'luasql.sqlite3'

local env = luasql.sqlite3()
local con = env:connect('database.s3db')

con:execute([[
CREATE TABLE IF NOT EXISTS users(
name varchar(50)
)
]])

con:execute([[
INSERT INTO users VALUES('Alguem');
INSERT INTO users VALUES('Outro');
INSERT INTO users VALUES('Mais Outro');
]])
cur = assert(con:execute([[
SELECT * FROM users
]]))
local result = {}
cur:fetch(result, 'a')

for i,v in pairs(result) do
    print(i,v)
end
cur:close()

con:close()
env:close()
os.execute('pause')

In this case, print only:

name Alguem

When should I print:

name Alguem
name Outro
name Mais Outro
    
asked by anonymous 03.03.2015 / 15:40

1 answer

1

I managed to fix it, there were two errors. The first one:

con:execute([[
INSERT INTO users VALUES('Alguem');
INSERT INTO users VALUES('Outro');
INSERT INTO users VALUES('Mais Outro');
]])

In this way, it only executes the 1 line, the correct way is:

con:execute("INTSERT INTO users VALUES('Alguem')")
con:execute("INTSERT INTO users VALUES('Outro')")
con:execute("INTSERT INTO users VALUES('Mais Outro')")

That is, each one is called in different "lines" / "functions".

The second error:

local result = {}
cur:fetch(result, 'a')

for i,v in pairs(result) do
    print(i,v)
end

This mode is wrong, as it says in the documentation on the fetch function, "Retrieves the next row of results.", so it always stays on the first result.

The right way is:

local row = cur:fetch({}, 'a')
while row do
    print('Name: '..row.name)
    row = cur:fetch(row, 'a')
end

Full, it looks like this:

require 'luasql.sqlite3'

local env = luasql.sqlite3()
local con = env:connect('database.s3db')

con:execute([[
CREATE TABLE IF NOT EXISTS users(
name varchar(50)
)
]])

con:execute("INSERT INTO users VALUES('Alguem');")
con:execute("INSERT INTO users VALUES('Outro');")
con:execute("INSERT INTO users VALUES('Mais Outro');")

cur = assert(con:execute([[
SELECT * FROM users
]]))

local row = cur:fetch({}, 'a')
while row do
    print('Name: '..row.name)
    row = cur:fetch(row, 'a')
end

cur:close()

con:close()
env:close()
os.execute('pause')
    
03.03.2015 / 17:02