Skip to content

SQL Extension

Dmitriy Zayceff edited this page May 10, 2015 · 11 revisions

To use the sql extension, you should add the jphp-sql-ext maven dependency (in build.gradle) and add the JDBC driver dependency for your database product (SQLite, MySQL, PostgreSQL, etc).

  • For example (SQLite):
dependencies {
    // ...
    
    compile 'org.develnext:jphp-sql-ext:<version>'
    compile 'org.xerial:sqlite-jdbc:3.8.7'
}
  • For MySQL: compile 'mysql:mysql-connector-java:5.1.35'
  • For PostgreSQL: compile 'org.postgresql:postgresql:9.4-1201-jdbc41'

To use other sql databases, you can search JDBC driver for <database name> maven in Google, for example.

Getting started

Before using you should install an sql driver:

use php\sql\SqlDriverManager;

SqlDriverManager::install('sqlite'); // or mysql or postres or JDBC Driver java class name

Get an sql connection of your database:

use php\sql\SqlDriverManager;

SqlDriverManager::install('sqlite');

$conn = SqlDriverManager::getConnection('sqlite:example.db'); // JDBC url without `jdbc:` prefix

Work with your database:

use php\sql\SqlResult;
use php\util\Flow;

$conn->query('create table person (id integer, name string)')->update();
$conn->query("insert into person values(?, ?)", [1, 'leo'])->update();
$conn->query("insert into person values(?, ?)", [2, 'yui'])->update();

// simple usage
foreach ($conn->query('select * from person') as $item) {
    var_dump($item->toArray());
}

// .. or We have used Flow class from JPHP standard library to lazy iterate on the results.
$array = Flow::of($conn->query('select * from person'))
    ->map(function (SqlResult $result) { return $result->toArray(); })
    ->toArray();

var_dump($array);
Clone this wiki locally