pub struct Connection(/* private fields */);mysql only.Expand description
An open connection to a MySQL database.
§Examples
Load a set of rows from a local MySQL database, and iterate over them.
use spin_sdk::mysql::{Connection, Decode, ParameterValue};
let db = Connection::open("mysql://root:my_password@localhost/mydb").await?;
let mut query_result = db.query(
"SELECT * FROM users WHERE age >= ?",
&[min_age.into()]
).await?;
while let Some(row) = query_result.next().await {
let name = row.get::<String>("name").unwrap();
println!("Found user {name}");
}
query_result.result().await?;Perform an aggregate (scalar) operation over a table. The result set contains a single column, with a single row.
use spin_sdk::mysql::{Connection, Decode};
let db = Connection::open("mysql://root:my_password@localhost/mydb").await?;
let mut query_result = db.query("SELECT COUNT(*) FROM users", &[]).await?;
assert_eq!(1, query_result.columns().len());
assert_eq!("COUNT(*)", query_result.columns()[0].name);
let rows = query_result.collect().await?;
assert_eq!(1, rows.len());
let count = &rows[0][0];Delete rows from a MySQL table. This uses Connection::execute()
instead of the query method.
use spin_sdk::mysql::{Connection, ParameterValue};
let db = Connection::open("mysql://root:my_password@localhost/mydb").await?;
db.execute(
"DELETE FROM users WHERE name = ?",
&["Baldrick".to_owned().into()]
).await?;Implementations§
Source§impl Connection
impl Connection
Sourcepub async fn open(address: impl Into<String>) -> Result<Self, Error>
pub async fn open(address: impl Into<String>) -> Result<Self, Error>
Open a connection to a MySQL database.
The address may be in connection string form ("host=... dbname=...")
or in URL form ("mysql://<host>/<dbname>?...").
Sourcepub async fn query(
&self,
statement: impl Into<String>,
params: impl Into<Vec<ParameterValue>>,
) -> Result<QueryResult, Error>
pub async fn query( &self, statement: impl Into<String>, params: impl Into<Vec<ParameterValue>>, ) -> Result<QueryResult, Error>
Query the database.
Use this function for queries that return rows (typically SELECT queries).
For side-effectful queries, see Connection::execute.
Sourcepub async fn execute(
&self,
statement: impl Into<String>,
params: impl Into<Vec<ParameterValue>>,
) -> Result<(), Error>
pub async fn execute( &self, statement: impl Into<String>, params: impl Into<Vec<ParameterValue>>, ) -> Result<(), Error>
Execute a command against the database.
Use this function for side-effectful queries (such as INSERT or DELETE queries).
For queries that return row data, see Connection::query.