Register forum user name Search FAQ

Database (SQLite)

MUSHclient from version 4.40 onwards has support for accessing SQLite 3 databases.


  • Databases are created and manipulated purely by script commands, generally intended to be inside plugins.

  • You can have any number of databases open at once. Each one has a name which is used by the script to refer to it.

  • Databases can be purely "in memory" by using the filename ":memory:".



General technique


  • Open the database with DatabaseOpen

  • Execute "action" SQL statements with DatabaseExec

  • To query data from the database:


    • Prepare an SQL statement with DatabasePrepare
    • Get column names with DatabaseColumnName or DatabaseColumnNames
    • Step through each row with DatabaseStep
    • Get column values with DatabaseColumnValue or DatabaseColumnValues
    • After all rows are extracted, finalize the statement with DatabaseFinalize


  • Close the database with DatabaseClose



For more information, see:


http://www.gammon.com.au/db


You can also use the Lua sqlite3 interface to work on SQLite databases, in Lua only.




Example of creating a database


db = "mainDatabase"  -- internal identifier

DatabaseOpen (db, GetInfo (66) .. "mytestdb.sqlite", 6)

DatabaseExec (db, [[
DROP TABLE IF EXISTS weapons;
CREATE TABLE weapons(
        weapon_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
        name      TEXT NOT NULL,
        damage    INT DEFAULT 10,
        weight    REAL
      );
      ]])
      
DatabaseClose (db)  -- close it


It is better to check the result from calling functions like DatabaseExec, otherwise they may silently fail (eg, with an SQL syntax error) like this:


status = DatabaseExec (db, [[
DROP TABLE IF EXISTS weapons;
CREATE TABLE weapons(
        weapon_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
        name      TEXT NOT NULL,
        damage    INT DEFAULT 10,
        weight    REAL
      );
      ]])
      
if status ~= sqlite3.OK then
  print ("Error creating weapons table: ", DatabaseError(db))
end -- if not OK


The documentation for DatabaseExec suggests a function (dbcheck) which can be used as a generic return-code checker.




Example of adding a row of data


DatabaseExec (db, "INSERT INTO weapons (name, damage) VALUES ('Nick''s sword', 42)")


Note that if you need to use quotes inside a string, the quotes must be doubled, as shown above.




Example of selecting some rows and displaying them

As described above, you need to "prepare" the SQL statement first. Once prepared you can find how many columns are in it, and the column names.

Then you "step" through the rows, one by one, getting the column values. These can then be printed, saved, or acted up.

Finally you "finalize" the SQL statement, releasing it so you can do another operation.


-- prepare a query
DatabasePrepare (db, "SELECT * FROM weapons ORDER BY name")

-- find the column names
names = DatabaseColumnNames (db)

-- find how many columns there are
cols = DatabaseColumns (db)

-- step to get the first row
rc = DatabaseStep (db)  -- read first row

-- now loop, displaying each row, and getting the next one
while rc == sqlite3.ROW do
  
  print ("")
  values = DatabaseColumnValues (db)

  for i = 1, cols do
    print (names [i], "=", values [i])
  end -- for each column

  rc = DatabaseStep (db)  -- read next row

end -- while loop

-- finished with the statement
DatabaseFinalize (db)


You should really check the return code from DatabasePrepare in case you have an error in the SQL statement, as shown above for DatabaseExec.




Example using the Lua interface


require "tprint"

-- make in-memory database
db = sqlite3.open_memory()

-- make a table for testing
db:exec  [[
          CREATE TABLE mobs (name, class, hp);
          INSERT INTO mobs VALUES("Naga", "mage", 666);
          INSERT INTO mobs VALUES("Wolf", "beast", 42);
          INSERT INTO mobs VALUES("Guard", "warrior", 100);
       ]]

-- prepare a SELECT statement
local stmt = db:prepare ("SELECT * FROM mobs")

-- loop until we get everything
while true do

  local result = stmt:step ()

  -- exit loop if done
  if result == sqlite3.DONE then
    break
  end -- if done

  -- should have ROW result
  assert (result == sqlite3.ROW, "Row not found")

  -- get all values into a table
  local row = stmt:get_named_values()

  -- display them
  print (string.rep ("-", 20))
  tprint (row)
  
end -- while

-- done with this statement
stmt:finalize ()

-- finished with database
db:close ()


See Also ...

Topics

Lua SQLite (database) interface
Scripting

Functions

(DatabaseChanges) Returns a count of the changes to the database by the most recent SQL statement
(DatabaseClose) Closes an SQLite database
(DatabaseColumnName) Find the name of a specified column returned by an SQL statement
(DatabaseColumnNames) Return a table of all the columns returned by an SQL statement
(DatabaseColumns) Find how many columns will be returned by an SQL statement
(DatabaseColumnText) Returns the contents of an SQL column, as text
(DatabaseColumnType) Returns the type of data in an SQL column
(DatabaseColumnValue) Returns the contents of an SQL column, as text, float, integer, or null
(DatabaseColumnValues) Returns the contents of all the SQL columns after a step
(DatabaseError) Returns an English string describing the most recent SQL error
(DatabaseExec) Executes SQL code against an SQLite database
(DatabaseFinalize) Finalizes (wraps up) a previously-prepared SQL statement
(DatabaseGetField) Returns a single field from an SQL database
(DatabaseInfo) Returns information about a database
(DatabaseLastInsertRowid) Returns the most recently automatically allocated database key
(DatabaseList) Lists all databases
(DatabaseOpen) Opens an SQLite database
(DatabasePrepare) Prepares an SQL statement for execution
(DatabaseReset) Resets a previously-prepared SQL statement to the start
(DatabaseStep) Executes a previously-prepared SQL statement
(DatabaseTotalChanges) Returns a count of the total changes to the database

(Help topic: general=database)

Documentation contents page


Search ...

Enter a search string to find matching documentation.

Search for:   

Information and images on this site are licensed under the Creative Commons Attribution 3.0 Australia License unless stated otherwise.