Sqlalchemy-core-using-textual-sql

提供:Dev Guides
移動先:案内検索

SQLAlchemyコア-テキストSQLの使用

SQLAlchemyでは、文字列を使用できます。これは、SQLが既知であり、動的な機能をサポートするステートメントの必要性が低い場合に使用します。 text()コンストラクトは、ほとんど変更されずにデータベースに渡されるテキストステートメントを作成するために使用されます。

以下のコードに示すように、テキストのSQL文字列を直接表す新しい TextClause を構築します-

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

プレーン文字列よりも* text()*が提供する利点は-

  • バインドパラメータのバックエンドニュートラルサポート
  • ステートメントごとの実行オプション *結果列のタイピング動作

text()関数には、名前付きコロン形式のBoundパラメーターが必要です。 データベースバックエンドに関係なく一貫しています。 パラメーターの値を送信するには、追加の引数としてそれらをexecute()メソッドに渡します。

次の例では、テキストSQLでバインドされたパラメータを使用します-

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()

text()関数は次のようにSQL式を構築します-

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

x = 'A’およびy = 'L’の値がパラメーターとして渡されます。 結果は、「A」と「L」の間の名前を持つ行のリストです-

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

text()コンストラクトは、TextClause.bindparams()メソッドを使用して事前に確立されたバインド値をサポートします。 パラメータは、次のように明示的に入力することもできます-

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()

また、* and _()*関数を使用して、text()関数を使用して作成されたWHERE句で複数の条件を組み合わせることができます。

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()

上記のコードは、IDが2より大きい「A」と「L」の間の名前を持つ行をフェッチします。 コードの出力は以下のとおりです-

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