|
| 1 | +--- |
| 2 | +title: 'Prepared Statements' |
| 3 | +sidebar_label: 'Prepared Statements' |
| 4 | +pagination_prev: 'reference/sql/subqueries' |
| 5 | +pagination_next: 'reference/sql/explain' |
| 6 | +sidebar_position: 4 |
| 7 | +--- |
| 8 | + |
| 9 | +## Inferred Types |
| 10 | + |
| 11 | +When a parameter type is not explicitly specified in a prepared statement, the type is inferred at execution time based on the provided argument. This approach helps simplify statement definitions and supports flexible query execution. |
| 12 | + |
| 13 | +**SQL Example** |
| 14 | + |
| 15 | +To create a prepared statement named `greater_than` that infers the type of its parameter: |
| 16 | + |
| 17 | +```sql |
| 18 | +PREPARE greater_than AS SELECT * FROM example WHERE a > $1; |
| 19 | +``` |
| 20 | + |
| 21 | +To execute the prepared statement with an integer argument: |
| 22 | + |
| 23 | +```sql |
| 24 | +EXECUTE greater_than(20); |
| 25 | +``` |
| 26 | + |
| 27 | +**Python Example** |
| 28 | + |
| 29 | +```python |
| 30 | +import adbc_driver_flightsql.dbapi |
| 31 | + |
| 32 | +with adbc_driver_flightsql.dbapi.connect("grpc://localhost:50051") as conn: |
| 33 | + with conn.cursor() as cur: |
| 34 | + cur.execute("PREPARE greater_than AS SELECT * FROM example WHERE a > $1;") |
| 35 | + cur.execute("EXECUTE greater_than(?)", (20,)) |
| 36 | + result = cur.fetchall() |
| 37 | + print(result) |
| 38 | +``` |
| 39 | + |
| 40 | +## Positional Arguments |
| 41 | + |
| 42 | +Prepared statements can use positional arguments to support multiple parameters. Each parameter is referenced by its position in the statement. |
| 43 | + |
| 44 | +**SQL Example** |
| 45 | + |
| 46 | +To create a prepared statement named `greater_than` with two parameters: |
| 47 | + |
| 48 | +```sql |
| 49 | +PREPARE greater_than(INT, DOUBLE) AS SELECT * FROM example WHERE a > $1 AND b > $2; |
| 50 | +``` |
| 51 | + |
| 52 | +To execute the prepared statement with integer and double arguments: |
| 53 | + |
| 54 | +```sql |
| 55 | +EXECUTE greater_than(20, 23.3); |
| 56 | +``` |
| 57 | + |
| 58 | +**Python Example** |
| 59 | + |
| 60 | +```python |
| 61 | +import adbc_driver_flightsql.dbapi |
| 62 | + |
| 63 | +with adbc_driver_flightsql.dbapi.connect("grpc://localhost:50051") as conn: |
| 64 | + with conn.cursor() as cur: |
| 65 | + cur.execute("PREPARE greater_than(INT, DOUBLE) AS SELECT * FROM example WHERE a > $1 AND b > $2;") |
| 66 | + cur.execute("EXECUTE greater_than(?, ?)", (20, 23.3)) |
| 67 | + result = cur.fetchall() |
| 68 | + print(result) |
| 69 | +``` |
0 commit comments