TUTORIAL 01 - Database handling
FUNCTIONS: NewDB( ), OpenDB( ), CloseDB( )
In this tutorial you will learn the how to handle an SDB database, how to create, open and finally close a database.
HOW TO CREATE A NEW DATABASE
The
first step is to build the record structure that describe the data that we will store in a single record, every record is composed by single fields each one with its own data type.
Suppose that we want tu build a database that holds the following informations:
   - Name
   - Surname
   - Age
   - Job
All we have to do is build a table that stores the above definition, every field in a table entry, starting from position 1, as follow:
-- Build a table holding the record structure
-- "name" is the fieldname and "type" is the field type
myrecord[1] = { name = "Name",    type = sdb.prefs.TYP_StringID }
myrecord[2] = { name = "Surname", type = sdb.prefs.TYP_StringID }
myrecord[3] = { name = "Age",     type = sdb.prefs.TYP_NumberID }
myrecord[4] = { name = "Job",     type = sdb.prefs.TYP_StringID }
Note that the above code can be written as follow too:
-- an alternative way to define table entries
myrecord[1] = { }
myrecord[1].name = "Name"
myrecord[1].type = sdb.prefs.TYP_StringID
myrecord[2] = { }
myrecord[2].name = "Surname"
myrecord[2].type = sdb.prefs.TYP_StringID
...
The
second step build the database file using the function
sdb.db.NewDB() that will use our table to define the file
-- Build the database file
filename, error = sdb.NewDB( "ram:mySdbDatabase", myrecord, 1 )
Let's explain the function:
"ram:mySdbDatabase" is the filename we want to use, the system will append the .sdb extension if not specified
myrecord is the record structure defined before
1 is a flag that means if the file exists overwrite it, can be omitted or set to 0, in both cases, if the file exists, an error will be returned.
As you can see the functions returns two values:
the first one is the final file name of the created database (including the path) or nil if the creation fails.
The second one is a warning/error message, or nil if all went well.
You can discard the returned values writing
-- Build the database file without error checking
sdb.NewDB( "ram:mySdbDatabase", myrecord, 1 )
but in this way you can't check if the database was successfully created or not, nor, you can be sure of the file name where the database has been stored.
The last optional step is the error checking
-- Checking for errors
if error ~= nil then
   print("Error!"..error)
   print("Database not created!")
else
   print("Database created successfully")
   print("Filename:"..filename)
end
Proceed to the second part >>