Luasql(Sqlite3) accepting only a "value"

Asked

Viewed 41 times

1

I’m trying to create a simple table, just with names, but when I enter a value, I can’t enter any more. Like I’m 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
  • I never used Luasql but it seems to be all right except for the assert, He’s supposed to be right there?

  • Yes, and even if you remove it, it still doesn’t work as desired.

1 answer

1


There were two mistakes. The first:

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

Thus, it runs only 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 is called in different "lines"/"functions".

The second mistake:

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 fetch, "Retrieves the next Row of Results." so it is always in 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

Complete, it was 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')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.