Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
R

rust-mysql-simple

> 数据库
Open source

Mysql client library implemented in rust.

693 stars0 likes3 views
WebsiteGitHub

About

Mysql client library implemented in rust.

mysql

This crate offers:

  • MySql database driver in pure rust;
  • connection pool.

Features:

  • macOS, Windows and Linux support;
  • TLS support via native-tls or rustls (see the SSL Support section);
  • MySql text protocol support, i.e. support of simple text queries and text result sets;
  • MySql binary protocol support, i.e. support of prepared statements and binary result sets;
  • support of multi-result sets;
  • support of named parameters for prepared statements (see the Named Parameters section);
  • per-connection cache of prepared statements (see the Statement Cache section);
  • buffer pool (see the Buffer Pool section);
  • support of MySql packets larger than 2^24;
  • support of Unix sockets and Windows named pipes;
  • support of custom LOCAL INFILE handlers;
  • support of MySql protocol compression;
  • support of auth plugins:
    • mysql_native_password - for MySql prior to v8;
    • caching_sha2_password - for MySql v8 and higher;
    • mysql_clear_password - opt-in (see [Opts::get_enable_cleartext_plugin].

Installation

Put the desired version of the crate into the dependencies section of your Cargo.toml:

toml
[dependencies]
mysql = "*"

Example

…

Crate Features

  • feature sets:

    • default – includes buffer-pool flate2/zlib and derive
    • default-rust - same as default but with flate2/rust_backend instead of flate2/zlib
    • minimal - includes flate2/zlib only
    • minimal-rust - includes flate2/rust_backend only
  • features:

    • buffer-pool – enables buffer pooling (see the Buffer Pool section)
    • derive – reexports derive macros under prelude (see [corresponding section][derive_docs] in the mysql_common documentation)
  • TLS/SSL related features:

    • native-tls – specifies native-tls as the TLS backend (see the SSL Support section)
    • rustls-tls – specifies rustls as the TLS backend using aws-lc-rs crypto provider (see the SSL Support section)
    • rustls-tls-ring – specifies rustls as the TLS backend using ring crypto provider (see the SSL Support section)
    • rustls - specifies rustls as the TLS backend without crypto provider (see the SSL Support section)
  • features proxied from mysql_common:

    • derive - see [this table][common_features].
    • chrono - see [this table][common_features].
    • time - see [this table][common_features].
    • bigdecimal - see [this table][common_features].
    • rust_decimal - see [this table][common_features].
    • frunk - see [this table][common_features].
    • binlog - see [this table][common_features].

Please note, that you'll need to reenable required features if you are using default-features = false:

toml
[dependencies]
# Lets say that we want to use only the `rustls-tls` feature:
mysql = { version = "*", default-features = false, features = ["minimal-rust", "rustls-tls"] }

API Documentation

Please refer to the [crate docs].

Basic structures

Opts

This structure holds server host name, client username/password and other settings, that controls client behavior.

URL-based connection string

Note, that you can use URL-based connection string as a source of an Opts instance. URL schema must be mysql. Host, port and credentials, as well as query parameters, should be given in accordance with the RFC 3986.

Examples:

rust
let _ = Opts::from_url("mysql://localhost/some_db")?;
let _ = Opts::from_url("mysql://[::1]/some_db")?;
let _ = Opts::from_url("mysql://user:pass%[email protected]:3307/some_db?")?;

Supported URL parameters (for the meaning of each field please refer to the docs on Opts structure in the create API docs):

  • user: string – MySql client user name
  • password: string – MySql client password;
  • db_name: string – MySql database name;
  • host: Host – MySql server hostname/ip;
  • port: u16 – MySql server port;
  • pool_min: usize – see [PoolConstraints::min];
  • pool_max: usize – see [PoolConstraints::max];
  • prefer_socket: true | false - see [Opts::get_prefer_socket];
  • tcp_keepalive_time_ms: u32 - defines the value (in milliseconds) of the tcp_keepalive_time field in the Opts structure;
  • tcp_keepalive_probe_interval_secs: u32 - defines the value of the tcp_keepalive_probe_interval_secs field in the Opts structure;
  • tcp_keepalive_probe_count: u32 - defines the value of the tcp_keepalive_probe_count field in the Opts structure;
  • tcp_connect_timeout_ms: u64 - defines the value (in milliseconds) of the tcp_connect_timeout field in the Opts structure;
  • tcp_user_timeout_ms - defines the value (in milliseconds) of the tcp_user_timeout field in the Opts structure;
  • stmt_cache_size: u32 - defines the value of the same field in the Opts structure;
  • enable_cleartext_plugin – see [Opts::get_enable_cleartext_plugin];
  • secure_auth – see [Opts::get_secure_auth];
  • reset_connection – see [PoolOpts::reset_connection];
  • check_health – see [PoolOpts::check_health];
  • compress - defines the value of the same field in the Opts structure. Supported value are:
    • true - enables compression with the default compression level;
    • fast - enables compression with "fast" compression level;
    • best - enables compression with "best" compression level;
    • 1..9 - enables compression with the given compression level.
  • socket - socket path on UNIX, or pipe name on Windows.

OptsBuilder

It's a convenient builder for the Opts structure. It defines setters for fields of the Opts structure.

rust
let opts = OptsBuilder::new()
    .user(Some("foo"))
    .db_name(Some("bar"));
let _ = Conn::new(opts)?;

Conn

This structure represents an active MySql connection. It also holds statement cache and metadata for the last result set.

Conn's destructor will gracefully disconnect it from the server.

Transaction

It's a simple wrapper on top of a routine, that starts with START TRANSACTION and ends with COMMIT or ROLLBACK.

rust
use mysql::*;
use mysql::prelude::*;

let pool = Pool::new(get_opts())?;
let mut conn = pool.get_conn()?;

let mut tx = conn.start_transaction(TxOpts::default())?;
tx.query_drop("CREATE TEMPORARY TABLE tmp (TEXT a)")?;
tx.exec_drop("INSERT INTO tmp (a) VALUES (?)", ("foo",))?;
let val: Option = tx.query_first("SELECT a from tmp")?;
assert_eq!(val.unwrap(), "foo");
// Note, that transaction will be rolled back implicitly on Drop, if not committed.
tx.rollback();

let val: Option = conn.query_first("SELECT a from tmp")?;
assert_eq!(val, None);

Pool

It's a reference to a connection pool, that can be cloned and shared between threads.

rust
use mysql::*;
use mysql::prelude::*;

use std::thread::spawn;

let pool = Pool::new(get_opts())?;

let handles = (0..4).map(|i| {
    spawn({
        let pool = pool.clone();
        move || {
            let mut conn = pool.get_conn()?;
            conn.exec_first::("SELECT ? * 10", (i,))
                .map(Option::unwrap)
        }
    })
});

let result: Result> = handles.map(|handle| handle.join().unwrap()).collect();

assert_eq!(result.unwrap(), vec![0, 10, 20, 30]);

Statement

Statement, actually, is just an identifier coupled with statement metadata, i.e an information about its parameters and columns. Internally the Statement structure also holds additional data required to support named parameters (see bellow).

rust
use mysql::*;
use mysql::prelude::*;

let pool = Pool::new(get_opts())?;
let mut conn = pool.get_conn()?;

let stmt = conn.prep("DO ?")?;

// The prepared statement will return no columns.
assert!(stmt.columns().is_empty());

// The prepared statement have one parameter.
let param = stmt.params().get(0).unwrap();
assert_eq!(param.schema_str(), "");
assert_eq!(param.table_str(), "");
assert_eq!(param.name_str(), "?");

Value

This enumeration represents the raw value of a MySql cell. Library offers conversion between Value and different rust types via FromValue trait described below.

FromValue trait

This trait is reexported from mysql_common create. Please refer to its [crate docs][mysql_common docs] for the list of supported conversions.

Trait offers conversion in two flavours:

  • from_value(Value) -> T - convenient, but panicking conversion.

    Note, that for any variant of Value there exist a type, that fully covers its domain, i.e. for any variant of Value there exist T: FromValue such that from_value will never panic. This means, that if your database schema is known, then it's possible to write your application using only from_value with no fear of runtime panic.

  • from_value_opt(Value) -> Option - non-panicking, but less convenient conversion.

    This function is useful to probe conversion in cases, where source database schema is unknown.

…

Row

Internally Row is a vector of Values, that also allows indexing by a column name/offset, and stores row metadata. Library offers conversion between Row and sequences of Rust types via FromRow trait described below.

FromRow trait

This trait is reexported from mysql_common create. Please refer to its [crate docs][mysql_common docs] for the list of supported conversions.

This conversion is based on the FromValue and so comes in two similar flavours:

  • from_row(Row) -> T - same as from_value, but for rows;
  • from_row_opt(Row) -> Option - same as from_value_opt, but for rows.

Queryable trait offers implicit conversion for rows of a query result, that is based on this trait.

…

Params

Represents parameters of a prepared statement, but this type won't appear directly in your code because binary protocol API will ask for T: Into, where Into is implemented:

  • for tuples of Into types up to arity 12;

    Note: singular tuple requires extra comma, e.g. ("foo",);

  • for IntoIterator> for cases, when your statement takes more than 12 parameters;

  • for named parameters representation (the value of the params! macro, described below).

rust
use mysql::*;
use mysql::prelude::*;

let mut conn = Conn::new(get_opts())?;

// Singular tuple requires extra comma:
let row: Option = conn.exec_first("SELECT ?", (0,))?;
assert_eq!(row.unwrap(), 0);

// More than 12 parameters:
let row: Option = conn.exec_first(
    "SELECT CONVERT(? + ? + ? + ? + ? + ? + ? + ? + ? + ? + ? + ? + ? + ? + ? + ?, UNSIGNED)",
    (0..16).collect::>(),
)?;
assert_eq!(row.unwrap(), 120);

Note: Please refer to the [mysql_common crate docs][mysql_common docs] for the list of types, that implements Into.

Serialized, Deserialized

Wrapper structures for cases, when you need to provide a value for a JSON cell, or when you need to parse JSON cell as a struct.

rust
use mysql::*;
use mysql::prelude::*;
use serde::{Deserialize, Serialize};

/// Serializable structure.
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Example {
    foo: u32,
}

// Value::from for Serialized will emit json string.
let value = Value::from(Serialized(Example { foo: 42 }));
assert_eq!(value, Value::Bytes(br#"{"foo":42}"#.to_vec()));

// from_value for Deserialized will parse json string.
let structure: Deserialized = from_value(value);
assert_eq!(structure, Deserialized(Example { foo: 42 }));

[QueryResult]

It's an iterator over rows of a query result with support of multi-result sets. It's intended for cases when you need full control during resul

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rustdatabasedrivermysqlrust

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库