Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add prepared statement example, etc #646

Merged
merged 4 commits into from
Dec 2, 2022
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions docs/database/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ ensure
end
```

Alternatively, you can use `DB.connect` method to open a single connection to the database instead of a pool.

## Exec

To execute sql statements you can use `Database#exec`
Expand Down Expand Up @@ -109,6 +111,26 @@ db.query("select name from contacts where age = ?", 33) do |rs|
end
```

Query parameters are effected under the covers with prepared statements (sometimes cached),
or insertion on the client side, depending on the driver, but will always avoid SQL Injection.

If you want to manually use prepared statements, you can with the `build` method:

```crystal
# MySQL
mysql_prepared_statement = mysql_db.build("select * from contacts where id=?")
# Postgres
postgres_prepared_statement = postgres_db.build("select * from contacts where id=$1")
# Use prepared statement:
prepared_statement.query(3) do |rs|
# ... use rs
end
prepared_statement.query(4) do |rs|
# ... use rs
end
prepared_statement.close
```

## Reading Query Results

When reading values from the database there is no type information during compile time that crystal can use. You will need to call `rs.read(T)` with the type `T` you expect to get from the database.
Expand Down