Skip to main content

How to inject database connection in Drupal 8

Database connection can be injected in class object using dependency injection.

We can also use service method
\Drupal::database() 

This way of using database is suitable for XXX.module file but in class we can use dependency injection.

Using dependency injection :-

Drupal\Core\Database\Connection class for database connection.

use Drupal\Core\Database\Connection;
use Symfony\Component\DependencyInjection\ContainerInterface;

class CustomClass {

  /**
   * The database connection to be used.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

  /**
   * @param \Drupal\Core\Database\Connection $database
   *   The database connection to be used.
   */
  public function __construct(Connection $database) {
    $this->database = $database;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $container->get('database')
  }

}

$container->get('database') here database is the service.


How to use it


For insert query :-
$query = $this->database->insert('custom_table')
        ->fields(['id', 'message'])
        ->values([1, 'some text']);
$result = $query->execute();


For checking table exists :-
$database_schema = $this->database->schema();
if (!($database_schema->tableExists('custom_table'))) {
  return FALSE;
} 

Comments

Popular posts from this blog

Use Case Diagram for Online Book Store

Online Movie Ticket Booking Sequence Diagram

Linear search & Binary search using Template

Write a program to search an element from a list. Give user the option to perform Linear or Binary search. Use Template functions. #include<iostream> using namespace std; template <class T> void Lsearch(T *a, T item, int n) { int z=0; for(int i=0;i<n;i++) { if(a[i]== item) { z=1; cout<<"\n Item found at position = "<<i+1<<"\n\n"; } else if(z!=1) { z=0; } } if(z==0) cout<<"\n Item not found in the list\n\n"; } template <class T> void Bsearch(T *a, T item, int n) { int beg=0,end=n-1; int mid=beg+end/2; while((a[mid]!=item) && (n>0)) { if(item>a[mid]) beg=mid; else end=mid; mid=(beg+end)/2; n--; } if(a[mid]==item) cout<<"\n Item found at position = "<<mid+1<<"\n\n"; else cout<<"\n Item not found in the list\n\n"; } void main() { int iarr[10] = {2,42,56,86,87,99,323,546,767,886};