Class

# Database

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## Description

The <span class="title-ref">Database</span> class is the base class for the <span class="title-ref">Database</span> subclasses that communicate with a variety of databases. Use one of the subclasses to connect to your <span class="title-ref">Database</span>.

## Properties

<div class="rst-class">

table-centered_columns_3_and_4

</div>

| Name                                  | Type                               | Read-Only | Shared |
|---------------------------------------|------------------------------------|-----------|--------|
| `DatabaseName<database.databasename>` | `String</api/data_types/string>`   |           |        |
| `Host<database.host>`                 | `String</api/data_types/string>`   |           |        |
| `MetaData<database.metadata>`         | `String</api/data_types/string>`   |           |        |
| `Password<database.password>`         | `String</api/data_types/string>`   |           |        |
| `Tag<database.tag>`                   | `Variant</api/data_types/variant>` |           |        |
| `UserName<database.username>`         | `String</api/data_types/string>`   |           |        |

## Methods

<div class="rst-class">

table-centered_column_4

</div>

| Name                                                | Parameters                                                                                                                                             | Returns                                                     | Shared |
|-----------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------|--------|
| `AddRow<database.addrow>`                           | tableName As `String</api/data_types/string>`, row As `DatabaseRow</api/databases/databaserow>`                                                        |                                                             |        |
|                                                     | tableName As `String</api/data_types/string>`, row As `DatabaseRow</api/databases/databaserow>`, idColumnName As `String</api/data_types/string>` = "" | `Integer</api/data_types/integer>`                          |        |
| `BeginTransaction<database.begintransaction>`       |                                                                                                                                                        |                                                             |        |
| `Close<database.close>`                             |                                                                                                                                                        |                                                             |        |
| `CommitTransaction<database.committransaction>`     |                                                                                                                                                        |                                                             |        |
| `Connect<database.connect>`                         |                                                                                                                                                        |                                                             |        |
| `ExecuteSQL<database.executesql>`                   | command As `String</api/data_types/string>`, `ParamArray</api/language/paramarray>` values() As `Variant</api/data_types/variant>`                     |                                                             |        |
| `Prepare<database.prepare>`                         | statement As `String</api/data_types/string>`                                                                                                          | `PreparedSQLStatement</api/databases/preparedsqlstatement>` |        |
| `RollbackTransaction<database.rollbacktransaction>` |                                                                                                                                                        |                                                             |        |
| `SelectSQL<database.selectsql>`                     | query As `String</api/data_types/string>`, `ParamArray</api/language/paramarray>` values() As `Variant</api/data_types/variant>`                       | `RowSet</api/databases/rowset>`                             |        |
| `TableColumns<database.tablecolumns>`               | tableName As `String</api/data_types/string>`                                                                                                          | `RowSet</api/databases/rowset>`                             |        |
| `TableIndexes<database.tableindexes>`               | tableName As `String</api/data_types/string>`                                                                                                          | `RowSet</api/databases/rowset>`                             |        |
| `Tables<database.tables>`                           |                                                                                                                                                        | `RowSet</api/databases/rowset>`                             |        |

## Property descriptions

<div id="database.databasename">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Database.DatabaseName

**DatabaseName** As `String</api/data_types/string>`

> The name of the <span class="title-ref">Database</span> to open.
>
> The *DatabaseName* is typically used with server databases (such as MySQL or PostgreSQL) to identify the specific <span class="title-ref">Database</span> to use on the server.
>
> This code connects to a PostgreSQL <span class="title-ref">Database</span> called "BaseballLeague":
>
> ``` xojo
> Var db As New PostgreSQLDatabase
>
> db.Host = "192.168.1.172"
> db.Port = 5432
> db.DatabaseName = "BaseballLeague"
> db.UserName = "broberts"
> db.Password = "streborb"
>
> Try
>   db.Connect
>   ' Use the database
> Catch error As DatabaseException
>   ' DB Connection error
>   MessageBox(error.Message)
> End Try
> ```

<div id="database.host">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Database.Host

**Host** As `String</api/data_types/string>`

> The <span class="title-ref">Database</span> host name or IP address of the <span class="title-ref">Database</span> server.
>
> This examples connects to a PostgreSQL <span class="title-ref">Database</span> called "BaseballLeague":
>
> ``` xojo
> Var db As New PostgreSQLDatabase
>
> db.Host = "192.168.1.172"
> db.Port = 5432
> db.DatabaseName = "BaseballLeague"
> db.UserName = "broberts"
> db.Password = "streborb"
>
> Try
>   db.Connect
>   ' Use the database
> Catch error As DatabaseException
>   ' DB Connection error
>   MessageBox(error.Message)
> End Try
> ```

<div id="database.metadata">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Database.MetaData

**MetaData** As `String</api/data_types/string>`

> Used to store custom data that doesn't belong in the other properties.

<div id="database.password">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Database.Password

**Password** As `String</api/data_types/string>`

> The password that is required for access to the <span class="title-ref">Database</span>. Typically used in conjunction with `UserName<database.username>`.
>
> This examples connects to a PostgreSQL <span class="title-ref">Database</span> called "BaseballLeague":
>
> ``` xojo
> Var db As New PostgreSQLDatabase
>
> db.Host = "192.168.1.172"
> db.Port = 5432
> db.DatabaseName = "BaseballLeague"
> db.UserName = "broberts"
> db.Password = "streborb"
>
> Try
>   db.Connect
>   ' Use the database
> Catch error As DatabaseException
>   ' DB Connection error
>   MessageBox(error.Message)
> End Try
> ```

<div id="database.username">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Database.UserName

**UserName** As `String</api/data_types/string>`

> The username that is required for access to the <span class="title-ref">Database</span>.
>
> This code connects to a PostgreSQL <span class="title-ref">Database</span> called "BaseballLeague":
>
> ``` xojo
> Var db As New PostgreSQLDatabase
>
> db.Host = "192.168.1.172"
> db.Port = 5432
> db.DatabaseName = "BaseballLeague"
> db.UserName = "broberts"
> db.Password = "streborb"
>
> Try
>   db.Connect
>   ' Use the database
> Catch error As DatabaseException
>   ' DB Connection error
>   MessageBox(error.Message)
> End Try
> ```

<div id="database.tag">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Database.Tag

**Tag** As `Variant</api/data_types/variant>`

> Used to store any value you wish to associated with this instance of the <span class="title-ref">database</span>.

## Method descriptions

<div id="database.addrow">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Database.AddRow

**AddRow**(tableName As `String</api/data_types/string>`, row As `DatabaseRow</api/databases/databaserow>`)

> Inserts *row* as a new row in *tableName*.
>
> Always look for a `DatabaseException</api/exceptions/databaseexception>` to verify whether or not the data was added.
>
> This code adds a row to an existing Team table with the columns "Name", "Coach" and "City". It's assumed that the variable db contains an active <span class="title-ref">Database</span> connection:
>
> ``` xojo
> Var row As New DatabaseRow
>
> ' ID will be updated automatically
> row.Column("Name") = "Penguins"
> row.Column("Coach") = "Bob Roberts"
> row.Column("City") = "Boston"
>
> Try  
>   db.AddRow("Team", row)
> Catch error As DatabaseException
>   MessageBox("DB Error: " + error.Message)
> End Try
> ```

**AddRow**(tableName As `String</api/data_types/string>`, row As `DatabaseRow</api/databases/databaserow>`, idColumnName As `String</api/data_types/string>` = "") As `Integer</api/data_types/integer>`

> Inserts *row* as a new row in *tableName* returning the newly assigned ID in the *idColumnName* column.
>
> Always look for a `DatabaseException</api/exceptions/databaseexception>` to verify whether or not the data was added.
>
> This code adds a row to an existing Team table with the columns "Name", "Coach" and "City" and returns the primary key created by and assigned to the primary key column (id in this case). It's assumed that the variable db contains an active <span class="title-ref">Database</span> connection:
>
> ``` xojo
> Var row As New DatabaseRow
>
> ' ID will be updated automatically
> row.Column("Name") = "Penguins"
> row.Column("Coach") = "Bob Roberts"
> row.Column("City") = "Boston"
>
> Var primaryKey As Integer
>
> Try  
>   primaryKey = db.AddRow("Team", row, "id")
> Catch error As DatabaseException
>   MessageBox("DB Error: " + error.Message)
> End Try
> ```

<div id="database.begintransaction">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Database.BeginTransaction

**BeginTransaction**

> Creates a new transaction. Changes to the <span class="title-ref">Database</span> made after this call can be saved with `CommitTransaction<database.committransaction>` or undone with `RollbackTransaction<database.rollbacktransaction>`.
>
> A `DatabaseException</api/exceptions/databaseexception>` will be raised if the transaction could not begin or another transaction is already in progress.
>
> You typically want to Commit changes after ensuring there were no <span class="title-ref">Database</span> errors:
>
> ``` xojo
> ' Prior DB code has run
> Try
>   DB.BeginTransaction
>   DB.ExecuteSQL("CREATE TABLE AddressBook name VARCHAR, email VARCHAR")
>   DB.CommitTransaction
> Catch error As DatabaseException
>   MessageBox("Error: " + error.Message)
>   DB.RollbackTransaction
> End Try
> ```

<div id="database.close">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Database.Close

**Close**

> Closes or disconnects the <span class="title-ref">Database</span>.
>
> Calling Close does not issue a Commit, but some databases will automatically Commit changes in a transaction when you Close the connection and some <span class="title-ref">Database</span> will automatically Rollback changes in a transaction when the connection is closed. Refer to the documentation for your <span class="title-ref">Database</span> to check what its behavior is.
>
> For desktop apps, you will often Connect to the <span class="title-ref">Database</span> when the app starts and Close it when the app quits.
>
> For web apps, you usually Connect to the <span class="title-ref">Database</span> when the Session starts and Close it when the Session quits.
>
> This code in the App.Closing event handler closes a previously connected \`Database\`:
>
> ``` xojo
> DB.Close ' DB is a property on App
> ```

<div id="database.committransaction">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Database.CommitTransaction

**CommitTransaction**

> Commits an open transaction. This permanently saves changes to the <span class="title-ref">Database</span>.
>
> A `DatabaseException</api/exceptions/databaseexception>` will be raised if the transaction could not be committed.
>
> You have to have an open transaction to be able to use CommitTransation. Use `BeginTransaction<database.begintransaction>` to begin a transaction:
>
> ``` xojo
> DB.BeginTransaction
> ```
>
> You typically want to commit changes after ensuring there were no <span class="title-ref">Database</span> errors:
>
> ``` xojo
> ' Prior DB code has run
> Try
>   DB.CommitTransaction
> Catch error As DatabaseException
>   MessageBox("Error: " + error.Message)
>   DB.RollbackTransaction
> End Try
> ```

<div id="database.connect">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Database.Connect

**Connect**

> Connects to the <span class="title-ref">Database</span> so that you can begin using it.
>
> <div class="warning">
>
> <div class="title">
>
> Warning
>
> </div>
>
> A `DatabaseException</api/exceptions/databaseexception>` will be raised if the connection could not be made.
>
> </div>
>
> This example connects to the <span class="title-ref">Database</span> object in the variable db:
>
> ``` xojo
> Try  
>   db.Connect
>   MessageBox("Connected!")
> Catch error As DatabaseException
>   MessageBox("Error connecting to the database: " + error.Message)
> End Try
> ```

<div id="database.executesql">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Database.ExecuteSQL

**ExecuteSQL**(command As `String</api/data_types/string>`, `ParamArray</api/language/paramarray>` values() As `Variant</api/data_types/variant>`)

> Used to execute an SQL command. Use this for commands that do not return any data, such as `CREATE TABLE` or `INSERT`. The *command* parameter contains the SQL statement.
>
> Passing values as parameters protects your <span class="title-ref">database</span> by automatically creating a `PreparedSQLStatement</api/databases/preparedsqlstatement>`.
>
> <div class="tip">
>
> <div class="title">
>
> Tip
>
> </div>
>
> You can also pass an `array</api/language/array>` of values as the first and only parameter instead of a `ParamArray</api/language/paramarray>`. This array **must** be of type `Variant</api/data_types/variant>`.
>
> </div>
>
> In this example, the <span class="title-ref">Database</span> is being updated without the use of parameters and thus leaves the <span class="title-ref">Database</span> vulnerable to a `SQL injection attack</topics/databases/protecting_your_database_from_attack>`:
>
> ``` xojo
> ' Updates a table in a SQLite database (db)
> Var sql As String = "UPDATE Customer SET City='" + CityField.Text + "' WHERE PostalCode='" + PostalCodeField.Text + "'"
>
> Try
>   db.ExecuteSQL(sql)
> Catch error As DatabaseException
>   MessageBox("DB Error: " + error.Message)
> End Try
> ```
>
> Here's the same example but using parameters which protects you against a `SQL injection attack</topics/databases/protecting_your_database_from_attack>`:
>
> ``` xojo
> ' Updates a table in a SQLite database (db)
> Var sql As String = "UPDATE Customer SET City=? WHERE PostalCode=?"
>
> Try
>   db.ExecuteSQL(sql, CityField.Text, PostalCode.Text)
> Catch error As DatabaseException
>   MessageBox("DB Error: " + error.Message)
> End Try
> ```
>
> The parameter values can also be passed in as a variant array:
>
> ``` xojo
> Var sql As String = "UPDATE Customer SET City=? WHERE PostalCode=?"
> Var values(1) As Variant
>
> values(0) = CityField.Text
> values(1) = PostalCode.Text
>
> Try
>   db.ExecuteSQL(sql, values)
> Catch error As DatabaseException
>   MessageBox("DB Error: " + error.Message)
> End Try
> ```
>
> This code creates the *Team* table:
>
> ``` xojo
> ' db is a SQLite database
> Var sql As String = "CREATE TABLE Team (ID INTEGER NOT NULL, Name TEXT, Coach TEXT, City TEXT, PRIMARY KEY(ID));"
>
> Try  
>   db.ExecuteSQL(sql)
>   MessageBox("Team table created successfully.")
> Catch error As DatabaseException
>   MessageBox("DB Error: " + error.Message)
> End Try
> ```

<div id="database.prepare">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Database.Prepare

**Prepare**(statement As `String</api/data_types/string>`) As `PreparedSQLStatement</api/databases/preparedsqlstatement>`

> Creates a PreparedSQLStatement using the SQL *statement* for use with the various <span class="title-ref">Database</span> prepared statement classes. A prepared statement is an SQL statement with parameters that has been pre-processed by the <span class="title-ref">Database</span> so that it can be executed more quickly if it is re-used with different parameters. Prepared statements also mitigate the risk of SQL injection in web apps.
>
> To create a prepared statement, you assign the value of Prepare to appropriate class for the <span class="title-ref">Database</span> you are using.
>
> Refer to the specific PreparedStatement class for the <span class="title-ref">Database</span> you are using to learn how to specify and bind parameters:
>
> - `MySQLPreparedStatement</api/databases/mysqlpreparedstatement>`
> - `ODBCPreparedStatement</api/databases/odbcpreparedstatement>`
> - `PostgreSQLPreparedStatement</api/databases/postgresqlpreparedstatement>`
> - `SQLitePreparedStatement</api/databases/sqlitepreparedstatement>`
>
> If the provided SQL statement has an error, a `DatabaseException</api/exceptions/databaseexception>` will occur when you call `SelectSQL<database.selectsql>` or `ExecuteSQL<database.executesql>`.
>
> [SQL Injection](http://en.wikipedia.org/wiki/SQL_injection) is a way to attack <span class="title-ref">Database</span>-driven applications.
>
> <div class="important">
>
> <div class="title">
>
> Important
>
> </div>
>
> This method is not currently supported for Android.
>
> `Database.SelectSQL<database.selectsql>` and `Database.ExecuteSQL<database.executesql>` both support prepared statements without the need to use any of the prepared statement classes. These cover most cases.
>
> </div>
>
> To create a prepared statement, you use the appropriate class for the <span class="title-ref">Database</span> you are using. For example, to create a prepared statement for PostgreSQL:
>
> ``` xojo
> ' db is a previously connected PostgreSQLDatabase object
> Var ps As PostgreSQLPreparedStatement = db.Prepare("SELECT * FROM Country WHERE code = $1")
> ```

<div id="database.rollbacktransaction">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Database.RollbackTransaction

**RollbackTransaction**

> Cancels an open transaction restoring the <span class="title-ref">Database</span> to the state it was in before the transaction began.
>
> A `DatabaseException</api/exceptions/databaseexception>` will be raised if the rollback could not be completed.
>
> You will generally want to rollback <span class="title-ref">Database</span> changes if a `DatabaseException</api/exceptions/databaseexception>` occurs within the transaction.
>
> <div class="important">
>
> <div class="title">
>
> Important
>
> </div>
>
> While rolling back a transaction restores the <span class="title-ref">database</span> to its previous state, it has no impact on the data you access in a `RowSet</api/databases/rowset>`. To update the `RowSet</api/databases/rowset>` so that its data matches the <span class="title-ref">database</span>, you will need to re-query the <span class="title-ref">database</span> to recreate the `RowSet</api/databases/rowset>`.
>
> </div>
>
> You have to have an open transaction to be able to use Rollback. Call `BeginTransaction<database.begintransaction>` to begin a transaction:
>
> ``` xojo
> DB.BeginTransaction
> ```
>
> This code uses rollback to revert <span class="title-ref">Database</span> changes in a transaction when an error occurs:
>
> ``` xojo
> ' Prior DB code has run
> Try
>   db.CommitTransaction
> Catch error As DatabaseException
>   MessageBox("Error: " + error.Message)
>   db.RollbackTransaction
> End If
> ```

<div id="database.selectsql">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Database.SelectSQL

**SelectSQL**(query As `String</api/data_types/string>`, `ParamArray</api/language/paramarray>` values() As `Variant</api/data_types/variant>`) As `RowSet</api/databases/rowset>`

> Executes a SQL SELECT statement and returns the results in a `RowSet</api/databases/rowset>`. *query* contains the SQL statement.
>
> Passing values as parameters protects your <span class="title-ref">database</span> by automatically creating a `PreparedSQLStatement</api/databases/preparedsqlstatement>`.
>
> <div class="tip">
>
> <div class="title">
>
> Tip
>
> </div>
>
> You can also pass an `array</api/language/array>` of values as the first and only parameter instead of a `ParamArray</api/language/paramarray>`. This array **must** be of type `Variant</api/data_types/variant>`.
>
> </div>
>
> <div class="warning">
>
> <div class="title">
>
> Warning
>
> </div>
>
> A `DatabaseException</api/exceptions/databaseexception>` will be raised if the SQL passed is invalid or if an error occurs.
>
> </div>
>
> Typically only SQL `SELECT` statements return a `RowSet</api/databases/rowset>`, but some databases return a `RowSet</api/databases/rowset>` for SQL commands such as `INSERT`, `UPDATE` or stored procedures.
>
> <div class="warning">
>
> <div class="title">
>
> Warning
>
> </div>
>
> While you can pass an entire valid SQL statement to SelectSQL with all values included, doing so can leave your <span class="title-ref">database</span> open to a `SQL injection attack</topics/databases/protecting_your_database_from_attack>`.
>
> </div>
>
> To avoid SQL injection attacks, use parameters in your SQL statement and then pass the values in as an array or parameter array. See the examples below.
>
> | Database                                                    | Parameter Format                                                                              |
> |-------------------------------------------------------------|-----------------------------------------------------------------------------------------------|
> | `MySQLCommunityServer</api/databases/mysqlcommunityserver>` | ?                                                                                             |
> | `ODBCDatabase</api/databases/odbcdatabase>`                 | ?                                                                                             |
> | `PostgreSQLDatabase</api/databases/postgresqldatabase>`     | \$1, \$2, etc.                                                                                |
> | `SQLiteDatabase</api/databases/sqlitedatabase>`             | ? (also ?NNN, :VVV, @VVV, \$VVV - [see docs](https://www.sqlite.org/lang_expr.html#varparam)) |
>
> This sample adds the names of all customers in a particular postal code to a ListBox. It passes the entire SQL select as a single statement and appends the value from a `TextField</api/user_interface/desktop/desktoptextfield>` called PostalCode, leaving the <span class="title-ref">Database</span> vulnerable to an `SQL injection attack</topics/databases/protecting_your_database_from_attack>`:
>
> ``` xojo
> ' db is a valid connection to a SQLite database
> Var rowsFound As RowSet
>
> Try
>   rowsFound = db.SelectSQL("SELECT * FROM Customer WHERE PostalCode=" + PostalCode.Text)
>
>   For Each row As DatabaseRow In rowsFound
>     ListBox1.AddRow(row.Column("Name").StringValue)
>   Next
>
>   rowsFound.Close
> Catch error As DatabaseException
>   MessageBox("Error: " + error.Message)
> End Try
> ```
>
> This is the same code as above but instead it uses a value identifier (?) and then passes the value in separately to avoid a [SQL injection attack](https://en.wikipedia.org/wiki/SQL_injection):
>
> ``` xojo
> ' db is a valid connection to a SQLite database
> Var rowsFound As RowSet
>
> Try
>   rowsFound = db.SelectSQL("SELECT * FROM Customer WHERE PostalCode=?", PostalCode.Text)
>
>   For Each row As DatabaseRow In rowsFound
>     ListBox1.AddRow(row.Column("Name").StringValue)
>   Next
>
>   rowsFound.Close
> Catch error As DatabaseException
>   MessageBox("Error: " + error.Message)
> End Try
> ```
>
> Multiple values can be passed to SelectSQL. In this example, Age and PostalCode are both `DesktopTextField</api/user_interface/desktop/desktoptextfield>` controls:
>
> ``` xojo
> ' db is a valid connection to a SQLite database
> Var rowsFound As RowSet
>
> Try
>   rowsFound = db.SelectSQL("SELECT * FROM Customer WHERE Age=? AND PostalCode=?", Age.Value, PostalCode.Text)
>
>   For Each row As DatabaseRow In rowsFound
>     ListBox1.AddRow(row.Column("Name").StringValue)
>   Next
>
>   rowsFound.Close
> Catch error As DatabaseException
>   MessageBox("Error: " + error.Message)
> End Try
> ```

<div id="database.tablecolumns">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Database.TableColumns

**TableColumns**(tableName As `String</api/data_types/string>`) As `RowSet</api/databases/rowset>`

> Returns a `RowSet</api/databases/rowset>` with information about all the columns (fields) in the specified *tableName*.
>
> <div class="note">
>
> <div class="title">
>
> Note
>
> </div>
>
> If an error occurs, a `DatabaseException</api/exceptions/databaseexception>` will be raised.
>
> </div>
>
> TableColumns returns a `RowSet</api/databases/rowset>` with these columns:
>
> - ColumnName: A string that is the name of the column.
> - FieldType: An integer that describes the type of the column (refer to the table below).
> - IsPrimary: A boolean that indicates if the column is part of the primary key.
> - NotNull: A boolean that indicates if the column can be set to NULL.
> - Length: An integer that describes the length of the field (for some text fields), the precision of numeric data (for some numeric fields) or the default value for a field (for SQLite columns).
> - cid: (SQLite Only) The ID of the column.
>
> `ODBC Databases</api/databases/odbcdatabase>` may return different columns depending upon the <span class="title-ref">database</span> to which you are connecting.
>
> This table identifies the Column Type based on the **FieldType** `Integer</api/data_types/integer>`:
>
> | Field Type            | Value | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
> |-----------------------|-------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
> | Null                  | 0     | Denotes the absence of any value, i.e., a missing value.                                                                                                                                                                                                                                                                                                                                                                                                     |
> | Byte                  | 1     | Stores the byte representation of a character string.                                                                                                                                                                                                                                                                                                                                                                                                        |
> | SmallInt              | 2     | A numeric data type with no fractional part. The maximum number of digits is implementation-specific, but is usually less than or equal to INTEGER. SQLite supports 4-byte smallints. If you are using another data source, check the documentation of your data source.                                                                                                                                                                                     |
> | Integer               | 3     | A numeric data type with no fractional part. The maximum number of digits is implementation-specific. SQLite supports 8-byte integer columns and the FieldType evaluates to 19 (64-bit integer).                                                                                                                                                                                                                                                             |
> | Char                  | 4     | Stores alphabetic data, in which you specify the maximum number of characters for the field, i.e., CHAR (20) for a 20 character field. If a record contains fewer than the maximum number of characters for the field, the remaining characters will be padded with blanks.                                                                                                                                                                                  |
> | Text or VarChar       | 5     | Stores alphabetic data, in which the number of characters vary from record to record, but you don't want to pad the unused characters with blanks. For example, VARCHAR (20) specifies a VARCHAR field with a maximum length of 20 characters.                                                                                                                                                                                                               |
> | Float                 | 6     | Stores floating-point numeric values with a precision that you specify, i.e., FLOAT (5).                                                                                                                                                                                                                                                                                                                                                                     |
> | Double                | 7     | Stores double-precision floating-point numbers.                                                                                                                                                                                                                                                                                                                                                                                                              |
> | Date                  | 8     | Stores year, month, and day values of a date in the format YYYY-MM-DD. The year value is four digits; the month and day values are two digits.                                                                                                                                                                                                                                                                                                               |
> | Time                  | 9     | Stores hour, minute, and second values of a time in the format HH:MM:SS. The hours and minutes are two digits. The seconds values is also two digits, may include a optional fractional part, e.g., 09:55:25.248. The default length of the fractional part is zero.                                                                                                                                                                                         |
> | TimeStamp             | 10    | Stores both date and time information in the format YYYY-MM-DD HH:MM:SS. The lengths of the components of a TimeStamp are the same as for Time and Date, except that the default length of the fractional part of the time component is six digits rather than zero. If a TimeStamp values has no fractional component, then its length is 19 digits If it has a fractional component, its length is 20 digits, plus the length of the fractional component. |
> | Currency              | 11    | This is a 64-bit fixed-point number format that holds 15 digits to the left of the decimal point and 4 digits to the right.                                                                                                                                                                                                                                                                                                                                  |
> | Boolean               | 12    | Stores the values of TRUE or FALSE.                                                                                                                                                                                                                                                                                                                                                                                                                          |
> | Decimal               | 13    | Stores a numeric value that can have both an integral and fractional part. You specify the total number of digits and the number of digits to the right of the decimal place, i.e., DECIMAL (5.2) specifies a decimal field that can contain values up to 999.99. DECIMAL (5) specifies a field that can contain values up to 99,999.                                                                                                                        |
> | Binary                | 14    | Stores code, images, and hexadecimal data. Consult the documentation of your data source for information on the maximum size of a Binary field.                                                                                                                                                                                                                                                                                                              |
> | Long Text (Blob)      | 15    | Stores a text object. Consult the documentation of your data source for information on the maximum size of a Blob.                                                                                                                                                                                                                                                                                                                                           |
> | Long VarBinary (Blob) | 16    | Stores a binary object. SQLite supports blobs of up to any size. Furthermore, a blob can be stored in a column of any declared data affinity. If you are using another data source, check the documentation of your data source.                                                                                                                                                                                                                             |
> | MacPICT               | 17    | Stores a Macintosh PICT image. SQLite does not support this data type. Use a Blob to store images.                                                                                                                                                                                                                                                                                                                                                           |
> | String                | 18    | Text up to about 2 billion bytes. The same as VarChar.                                                                                                                                                                                                                                                                                                                                                                                                       |
> | Int64                 | 19    | Stores a 64-bit integer. Integer fields in SQLite are 64 bits and FieldType returns 19.                                                                                                                                                                                                                                                                                                                                                                      |
> | Unknown               | 255   | Unrecognized data type.                                                                                                                                                                                                                                                                                                                                                                                                                                      |
>
> <div class="note">
>
> <div class="title">
>
> Note
>
> </div>
>
> Depending upon the version you are using, only a subset of these types may be supported.
>
> </div>
>
> The following code creates a table and then display each column name one at a time:
>
> ``` xojo
> Var dbFile As FolderItem = New FolderItem("mydb.sqlite", FolderItem.PathModes.Native)
>
> If dbFile.Exists Then
>   dbFile.Remove
> End If
>
> Var db As SQLiteDatabase = New SQLiteDatabase
> db.DatabaseFile = dbFile
>
> Try
>   db.CreateDatabase
>   db.ExecuteSQL("CREATE TABLE Invoices (ID INTEGER, CustID INTEGER, Amount Double, Note TEXT)")
>
>   Var columns As RowSet = db.TableColumns("Invoices")
>
>   For Each c As DatabaseRow In columns
>     MessageBox("Column: " + c.Column("ColumnName").StringValue)
>   Next
> Catch error As IOException
>   MessageBox("The database could not be created: " + error.Message)
> Catch error As DatabaseException
>   MessageBox("Database error: " + error.Message)
> End Try
> ```

<div id="database.tableindexes">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Database.TableIndexes

**TableIndexes**(tableName As `String</api/data_types/string>`) As `RowSet</api/databases/rowset>`

> Returns a `RowSet</api/databases/rowset>` containing the list of indexes for the passed *tableName*. Returns `Nil</api/language/nil>` if the table has no indexes or the <span class="title-ref">Database</span> source does not support indexes.
>
> A `DatabaseException</api/exceptions/databaseexception>` will be raised if an error occurs.
>
> The `RowSet</api/databases/rowset>` returns one row for each index on the table and it has one field: IndexName As `String</api/data_types/string>`.
>
> This code displays the indexes for the "Invoices" table (if it exists) in the specified SQLite \`Database\`:
>
> ``` xojo
> Var dbFile As FolderItem = FolderItem.ShowOpenFileDialog("")
>
> If dbFile <> Nil Then
>   Var db As New SQLiteDatabase
>
>   Try
>     db.Connect
>
>     Var indexRS As RowSet = db.TableIndexes("Invoices") ' A table with indexes in the SQLite DB
>
>     For Each row As DatabaseRow In indexRS
>       MessageBox("Index: " + row.ColumnAt(0).StringValue)
>     Next
>
>     indexRS.Close
>   Catch error As NilObjectException
>     MessageBox("This database has no indexes.")
>   Catch error As DatabaseException
>     MessageBox("Could not connect to database. Error: " + error.Message)
>   End Try
> End If
> ```

<div id="database.tables">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Database.Tables

**Tables** As `RowSet</api/databases/rowset>`

> Returns a `RowSet</api/databases/rowset>` with a list of all tables in the <span class="title-ref">Database</span>.
>
> A `DatabaseException</api/exceptions/databaseexception>` will be raised if an error occurs.
>
> Tables returns a `RowSet</api/databases/rowset>` with one field: TableName As `String</api/data_types/string>`.
>
> The following code gets and displays the table names for the connected \`Database\`:
>
> ``` xojo
> ' App.db is a connected database
> Var tables As RowSet = App.db.Tables
>
> Try
>   For Each row As DatabaseRow In tables
>     MessageBox(row.ColumnAt(0).StringValue)
>   Next
>
>   tables.Close
> Catch error As NilObjectException
>   MessageBox("This database has no tables.")
> End Try
> ```

## Notes

<div id="/api/databases/database/database_classes">

<span class="title-ref">Database</span> classes \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*

</div>

The following subclasses of <span class="title-ref">Database</span> are included. Everything other than `SQLiteDatabase</api/databases/sqlitedatabase>` requires that you copy the appropriate plugin to your Plugins folder.

| Class                                                       | Description                                                                        |
|-------------------------------------------------------------|------------------------------------------------------------------------------------|
| `MySQLCommunityServer</api/databases/mysqlcommunityserver>` | Supports the MySQL Community edition server. Use MySQLCommunityPlugin.xojo_plugin. |
| `ODBCDatabase</api/databases/odbcdatabase>`                 | Supports ODBC-based databases. Use ODBCPlugin.xojo_plugin.                         |
| `PostgreSQLDatabase</api/databases/postgresqldatabase>`     | Supports PostgreSQL. Use PostgreSQLPlugin.xojo_plugin.                             |
| `SQLiteDatabase</api/databases/sqlitedatabase>`             | Supports the built-in SQLite data source.                                          |

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

<div id="/api/databases/database/3rd_party_database_plugins">

3rd party <span class="title-ref">database</span> plugins \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*

</div>

The following <span class="title-ref">Database</span> plugins are also available. Contact the vendor for more information on how to use them.

| Class                                                                     | Description                                                                                                                                                                                                                                                                                                                       |
|---------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [cubeSQL](http://www.sqlabs.com)                                          | Adds support for cubeSQL Server, a <span class="title-ref">database</span> server built on SQLite.                                                                                                                                                                                                                                |
| [FrontBase](http://www.frontbase.com)                                     | Adds support for the FrontBase <span class="title-ref">database</span>.                                                                                                                                                                                                                                                           |
| [Valentina](http://www.valentina-db.com)                                  | Adds support for the Valentina stand-alone and server <span class="title-ref">databases</span>.                                                                                                                                                                                                                                   |
| [MBS SQL Plugin](http://www.monkeybreadsoftware.de/xojo/plugin-sql.shtml) | Adds support for the various server <span class="title-ref">databases</span> including CubeSQL, Centura SQLBase, DB2, Firebird, Informix, InterBase, MariaDB, Microsoft Access, Microsoft SQL Server, MySQL, ODBC, Oracle <span class="title-ref">Database</span> Server, PostgreSQL, SQL Anywhere, SQLite, SQLCipher and Sybase. |

## Sample code

The following code creates a SQLite <span class="title-ref">Database</span> and uses ExecuteSQL to create a table.

``` xojo
Var dbFile As New FolderItem("MyDB.sqlite", FolderItem.PathModes.Native)  
Var db As SQLiteDatabase = New SQLiteDatabase

db.DatabaseFile = dbFile

Try
  db.CreateDatabase

  Var sql As String = "CREATE TABLE Team (ID INTEGER NOT NULL, Name TEXT, Coach TEXT, City TEXT, PRIMARY KEY(ID));"

  db.ExecuteSQL(sql)
Catch error As DatabaseException
  MessageBox("Database error: " + error.Message)
End Try
```

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

The following example inserts a row in this table:

``` xojo
Var row As New DatabaseRow

' ID will be updated automatically
row.Column("Name") = "Penguins"
row.Column("Coach") = "Bob Roberts"
row.Column("City") = "Boston"

Try
  db.AddRow("Team", row)
Catch error As DatabaseException
  MessageBox("DB Error: " + error.Message)
End Try
```

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

This code gets the data from the Team table and displays it:

``` xojo
Var sql As String = "SELECT * FROM Team ORDER BY Name"
Var rows As RowSet = db.SelectSQL(sql)

If rows <> Nil Then
  For each row As DatabaseRow In rows
    MessageBox(row.Column("Name").StringValue + " " + row.Column("City").StringValue)
  Next
  rows.Close
End If
```

## Compatibility

|                       |     |
|-----------------------|-----|
| **Project Types**     | All |
| **Operating Systems** | All |

<div class="seealso">

`Object</api/data_types/additional_types/object>` parent class; `DatabaseColumn</api/databases/databasecolumn>`, `DatabaseException</api/exceptions/databaseexception>`, `DatabaseRow</api/databases/databaserow>`. `MySQLCommunityServer</api/databases/mysqlcommunityserver>`, `ODBCDatabase</api/databases/odbcdatabase>`, `PostgreSQLDatabase</api/databases/postgresqldatabase>`, `PreparedSQLStatement</api/databases/preparedsqlstatement>`, `RowSet</api/databases/rowset>`, `SQLiteDatabase</api/databases/sqlitedatabase>` classes.

</div>
