SQLAlchemy Core - Utilizzo di SQL testuale

SQLAlchemy ti consente di usare solo stringhe, per quei casi in cui l'SQL è già noto e non c'è una forte necessità per l'istruzione di supportare le funzionalità dinamiche. Il costrutto text () viene utilizzato per comporre un'istruzione testuale che viene passata al database per lo più invariata.

Costruisce un nuovo TextClause, che rappresenta una stringa SQL testuale direttamente come mostrato nel codice seguente -

from sqlalchemy import text
t = text("SELECT * FROM students")
result = connection.execute(t)

I vantaggi text() fornisce su una semplice stringa sono -

  • supporto indipendente dal backend per i parametri di binding
  • opzioni di esecuzione per istruzione
  • comportamento di digitazione nella colonna dei risultati

La funzione text () richiede parametri Bound nel formato due punti denominato. Sono coerenti indipendentemente dal backend del database. Per inviare valori per i parametri, li passiamo al metodo execute () come argomenti aggiuntivi.

L'esempio seguente utilizza parametri associati in SQL testuale:

from sqlalchemy.sql import text
s = text("select students.name, students.lastname from students where students.name between :x and :y")
conn.execute(s, x = 'A', y = 'L').fetchall()

La funzione text () costruisce l'espressione SQL come segue:

select students.name, students.lastname from students where students.name between ? and ?

I valori di x = "A" e y = "L" vengono passati come parametri. Il risultato è un elenco di righe con nomi compresi tra "A" e "L" -

[('Komal', 'Bhandari'), ('Abdul', 'Sattar')]

Il costrutto text () supporta valori vincolati prestabiliti utilizzando il metodo TextClause.bindparams (). I parametri possono anche essere digitati esplicitamente come segue:

stmt = text("SELECT * FROM students WHERE students.name BETWEEN :x AND :y")

stmt = stmt.bindparams(
   bindparam("x", type_= String), 
   bindparam("y", type_= String)
)

result = conn.execute(stmt, {"x": "A", "y": "L"})

The text() function also be produces fragments of SQL within a select() object that 
accepts text() objects as an arguments. The “geometry” of the statement is provided by 
select() construct , and the textual content by text() construct. We can build a statement 
without the need to refer to any pre-established Table metadata. 

from sqlalchemy.sql import select
s = select([text("students.name, students.lastname from students")]).where(text("students.name between :x and :y"))
conn.execute(s, x = 'A', y = 'L').fetchall()

Puoi anche usare and_() funzione per combinare più condizioni nella clausola WHERE creata con l'aiuto della funzione text ().

from sqlalchemy import and_
from sqlalchemy.sql import select
s = select([text("* from students")]) \
.where(
   and_(
      text("students.name between :x and :y"),
      text("students.id>2")
   )
)
conn.execute(s, x = 'A', y = 'L').fetchall()

Il codice precedente recupera le righe con nomi compresi tra "A" e "L" con id maggiore di 2. L'output del codice è fornito di seguito:

[(3, 'Komal', 'Bhandari'), (4, 'Abdul', 'Sattar')]