Database
Nette Framework provides a powerful layer for accessing your database easily.
- composes SQL queries with ease
- easily fetches data
- uses efficient queries and does not transmit unnecessary data
The Nette Database Core is a wrapper around the PDO and provides core functionality.
The Nette Database Explorer layer helps you to fetch database data more easily and in a more optimized way.
Creating a connection
To create a new database connection just create a new instance of Nette\Database\Connection class:
$connection = new Nette\Database\Connection($dsn, $user, $password);
Database server | DSN name | Core support | Explorer support |
---|---|---|---|
MySQL | mysql | YES | YES |
PostgreSQL | pgsql | YES | YES |
Sqlite 3 | sqlite | YES | YES |
Sqlite 2 | sqlite2 | YES | – |
Oracle | oci | YES | – |
MS SQL (PDO_SQLSRV) | sqlsrv | YES | YES |
MS SQL (PDO_DBLIB) | mssql | YES | – |
ODBC | odbc | YES | – |
The 4th optional parameter of the connection constructor allows you to specify some options. These options are passed to the PDO constructor and the internal driver constructor, so they can contain a configuration for both the PDO instance and the driver instance.
If you want that connection with the database server is not created immediately after an instance of Connection
is
created but only when the database is used, you can do so by setting the configuration to 'lazy' => TRUE
.
The internal driver class name is detected by provided DSN. However, you can provide you own implementation of an internal
driver. To do this, pass your driver name as an option with the driverClass
key.
$connection = new Connection($dsn, $user, $password, array(
'lazy' => FALSE,
'driverClass' => 'App\YourSpecificDriverImplementationName'
));
The easiest way to create a connection is to configure one in your application config, which allows you create multiple connections and helps you to add database panel to Tracy debug bar.
database:
default:
dsn: "mysql:host=127.0.0.1;dbname=test"
user: "root"
password: "password"
options: [PDO::MYSQL_ATTR_COMPRESS = true]
debugger: true # debugger bar panel
explain: true # explain queries in debugger bar
conventions: discovered # or static or name of your class, default is discovered
autowired: true
anotherConnection:
dsn: ...
autowired: false
Queries
Database\Connection allows you to easily query your database by calling query
method, which returns ResultSet.
$connection->query('INSERT INTO users', array( // an array can be a parameter
'name' => 'Jim',
'created' => new DateTime, // or a DateTime object
'avatar' => fopen('image.gif', 'r'), // or a file
), ...); // it is even possible to use multiple inserts
$connection->query('UPDATE users SET ? WHERE id=?', $data, $id);
$connection->query('SELECT * FROM categories WHERE id=?', 123)->dump();