Lua allows access to the database

 

  Lua itself does not provide functions to access the database, but with external extensions we can easily achieve a variety of operations on the database, here to introduce such an extension library - LuaSQL, you can get it in the download area.

  LuaSQL defines a simple object-oriented API, which, Lua can access a variety of popular databases (eg PostgreSQL, ODBC, JDBC, MySQL, SQLite, Oracle and ADO, etc.) in a uniform way.

  LuaSQL luasql defines a name for a global table (with the initialization function in Lua luaopen_luasql drivername  generated), this table is stored initialization method of loading a database driven. These methods can create an environment object, the object of these environments, you can create a connection object database. Connection object can perform various SQL statements, and ultimately generate cursor object.

Environment Object

  Environment objects are created by the various databases stored in the initialization function luasql table, the names of these functions and their corresponding database name is the same. E.g:

env = luasql.odbc ()
  This will create an environment object using the ODBC driver. JDBC driver rather special, you also have to let it know which internal driver should use, so when you create the environment object, you should drive class name passed to the luasql.jdbc function as a parameter. E.g:

env = luasql.jdbc("com.mysql.jdbc.Driver")

method

env: close ()
  closed environment object. We should call this function must only after all the database connections associated with it are closed.
  Returns: Close success returns true, fails to close or environment object has been closed returns false.

env: connect (sourcename [, username [, password]])
  is connected to a data source (SourceName) with the specified username (username) and a password (password).
  sourcename vary depending on the database-driven. Some use only a simple database name can be, for example, MySQL, PostgreSQL and SQLite; ODBC driver needs a DSN name; Oracle driver requires a service name; JDBC driver you need a string, like "jdbc: <database system>: // <database name> "the same.
  See also: PostgreSQL and MySQL extension extension.
  Return Value: a connection object.

Connection object

  Contains special connection object attribute data source connection, it is environment: connect created.

method

conn: close ()
  closes the database connection. Only in the case of all cursors are closed can succeed to close the connection.
  Returns: Close success returns true, or failure to close the connection has been closed returns false.

conn: commit ()
  Commits the current transaction. This method does not work properly in the database does not support transactions. Returns: submit returns true success, or failure to submit the database does not support transaction processing returns false.

conn: execute (statement) 
  Executes the given SQL statement
  Returns: a cursor object, or a number that indicates there is recorded by this statement affect how many.

conn: rollback ()
  to roll back the current transaction. This method does not work properly in the database does not support transactions. Returns: the successful rollback true, or failure to roll back the database does not support transaction processing returns false.

conn: setautocommit (boolean) 
  to open or close the "auto-commit transaction" function. This method does not work properly in the database does not support transactions. In the single-database support transactions do not support auto-commit transaction processing, database-driven based on different and have different results.
  Returns: Returns true setting success, or failure to set the database does not support transaction processing returns false.

The cursor object

  Cursor object contains various methods of extracting data from the results of an SQL statement. It is a connection: execute created.

method  

cur: close ()
  Closes the cursor object.
  Returns: Close success returns true, or failure to close the cursor object has been closed returns false.

cur: fetch ([table [, modestring]])
  to obtain the next record the results of the SQL statement results.
  If you do not pass any arguments when calling this method, the results will be returned directly to the caller of the method. If the passed parameters table, the results are copied into a table (table in Lua concepts) in and returned. At the same time, you can also specify a mode parameter indicating so a table is returned. It has the following two values:

"n" 
  results numerically indexed table identifier (default)

"a" 
  results in alphabetical index identifier

  Numeric index position identifier field order determined by the latter in the SELECT SQL statement; letter identifier index according to the name of the field is given by.
  The optional parameter table is used to store the next record.
  This method does not guarantee the return type of the result, to determine which database driver you used is made. For now, PostgreSQL, and MySQL will drive all of the results are converted to a string, and the Oracle ODBC driver Lua will return a value of type field type according to the corresponding
  Return Value: result data as described above, or in the absence of any returns nil when recording results. Note that this is not the only case return nil when valid results obtained may also return nil.

cur: getcolnames ()
  Return value: a list of field names thereof.

cur: getcoltypes () 
  Return value: a list of field types.

PostgreSQL extensions

  In addition to the above-mentioned general characteristics of methods, PostgreSQL drive additionally provides the following features:

the env: Connect (SourceName [, username [, password [, hostname [, Port]]]])
  the PostgreSQL driving This method also provides two additional optional parameter that specifies the host name and port number for the connection. Of course, you can only land one parameter can contain all connection information, like PostgreSQL manual PQconnectdb parameters as a function (for example, Environment: Connect ( "dbname = < name > = the User < username >"))
  See : environment objects.
  Return Value: a connection object.

cur: numrows ()
  See also: cursor objects
  Returns: the number of records the SQL query results.

 MySQL extension

  In addition to the above-mentioned general characteristics of methods, MySQL driver additionally provides the following features:

the env: Connect (SourceName [, username [, password [, hostname [, Port]]]])
  the MySQL driving This method also provides two additional optional parameter that specifies the host name and port number for the connection.
  See also: environment objects.
  Return Value: a connection object.

Oracle Extended

  In addition to the above-mentioned general characteristics of methods, Oracle drive additionally provides the following features:

cur: numrows ()
  See also: cursor objects
  Returns: the number of records the SQL query results.


The following is a simple example of the access by the Access Lua

- Load ODBC external extensions
the Assert (loadlib ( "ODBC.DLL", "luaopen_luasqlodbc")) ()

- Object Creation Environment
env = the Assert (luasql.odbc ())

- connect to the database
con = assert (env: connect ( "luatest", - DSN name
                           "username", - username
                           "password")) - password

- players delete data in a database table
assert (con: execute "DROP tABLE players")

- Create a data table players
Assert (CON: Execute [[
  the CREATE TABLE players (
    name VARCHAR (50),
    class VARCHAR (50)
  )
]])


- to add records to
List = {
  {name = "Gammon, Nick", class = "MAGE",},
  {name = "David Haley", class = "Warrior",},
  {name = "Shadowfyr", class = "Priest",}
}

for I, P in pairs (List) do
  Assert (CON : execute (String.Format ([[
    the INSERT the INTO Players
    the VALUES ( '% S', '% S')]], p.name, p.class)
  ))
End - for Loop

- execute a query, returns the cursor object
CUR = Assert (CON: Execute ( "Players from the SELECT *"))

- all records in the printing result
row = cur: fetch ({} , "a")

while row do
  print ( "\ n ------ new record --------- \ the n-")
  table.foreach (Row, Print)
  
  - repeated use of the table, to save resources
  row = cur: fetch ( Row, "a")
End - the while Loop

- closed and all database objects related to
CUR: use Close ()
CON: use Close ()
env: use Close ()

The following procedure is mysql database manipulation Lua

require "luasql.mysql"


- Object Creation Environment
env = luasql.mysql ()

- connect to the database
conn = env: connect ( "database name", "username", "password", "IP address", port)

- coded formatting database
Conn: execute "the SET NAMES GB2312"

- performing a database operation
CUR = Conn: execute ( "SELECT * from Role")

Row = CUR: FETCH ({}, "a")

- created file object
file = io.open ( "role.dat", "W +");

the while Row do
    var = String.Format ( "% D% S \ n-", row.id, row.name)

    Print (var)

    File: Write (var)

    Row = CUR: FETCH (Row, "A")
End


file: use Close () - close the file object
conn: close () - close the database connection
env: close () - close the database environment

Guess you like

Origin www.cnblogs.com/welcome-to-fang-qi-blog/p/12054074.html