driver
pub fn driver() driver.DriverPurpose
Return the database driver instance implementing driver.Driver.
Parameters
No arguments are required.
Returns
driver.Driver — a value of this type
#github.com/xulang-org/packages/mysqlMySQL/MariaDB database/sql driver. This driver is intentionally protocol-native: it does not require libmysqlclient, CGO, or a platform-specific runtime helper. It supports the text protocol, transactions, Prepare-shaped statements, and the mysql_native_password authentication plugin. `?` parameters are escaped by the driver before COM_QUERY is sent; placeholders inside SQL strings and comments are left untouched. TLS is negotiated with CLIENT_SSL after the server greeting; caching_sha2_password remains explicitly rejected until its RSA exchange is implemented. DSNs accepted by parse_dsn/open user:password@tcp(127.0.0.1:3306)/database?tls=false mysql://user:password@127.0.0.1:3306/database Defaults are host=127.0.0.1, port=3306, database=user.
github.com/xulang-org/packages · 1.17.2 · Install and use
These sources come from the official examples repository and can be copied or downloaded. Run them with a local Xu SDK in the complete project; network, database, and desktop examples require the corresponding services or assets.
18_database_mysql/main.xu@main
#database/sql
mysql #github.com/xulang-org/packages/mysql
#os
// MySQL/MariaDB:XU_MYSQL_DSN 可覆盖本地开发默认值。
// 驱动是普通 XU 包,通过 database/sql 接口使用,不依赖编译器内建。
fn main() int {
$dsn := os.getenv("XU_MYSQL_DSN")
if dsn.len == 0 {
dsn = "root:root@tcp(127.0.0.1:3306)/xu_demo?tls=false"
}
$db := sql.open(mysql.driver(), dsn)
db.ping() >>> (err) {
println("MySQL ping failed")
println(err.msg())
<< 1
}
db.exec("DROP TABLE IF EXISTS xu_people") >>> (err) {
println(err.msg())
<< 1
}
db.exec("CREATE TABLE xu_people (id INTEGER PRIMARY KEY, name VARCHAR(100) NOT NULL, active BOOLEAN NOT NULL)") >>> (err) {
println(err.msg())
<< 1
}
first := db.exec(
"INSERT INTO xu_people (id, name, active) VALUES (?, ?, ?)",
1,
"Ada",
true
) >>> (err) {
println(err.msg())
<< 1
}
println("inserted=" + str(first.rows_affected()))
$insert_person := db.prepare(
"INSERT INTO xu_people (id, name, active) VALUES (?, ?, ?)"
) >>> (err) {
println(err.msg())
<< 1
}
insert_person.exec(2, "Lin", true) >>> (err) {
println(err.msg())
<< 1
}
insert_person.close()
$tx := db.begin() >>> (err) {
println(err.msg())
<< 1
}
tx.exec(
"INSERT INTO xu_people (id, name, active) VALUES (?, ?, ?)",
3,
"Grace",
true
) >>> (err) {
println(err.msg())
<< 1
}
tx.commit() >>> (err) {
println(err.msg())
<< 1
}
$rows := db.query("SELECT id, name FROM xu_people ORDER BY id") >>> (err) {
println(err.msg())
<< 1
}
while rows.next() {
values := rows.take() >>> (err) {
println(err.msg())
<< 1
}
id := values[0] as int
name := values[1] as string
println(str(id) + ": " + name)
}
if rows.err().len > 0 {
println(rows.err())
<< 1
}
rows.close()
row := db.query_row("SELECT name FROM xu_people WHERE id = ?", 2)
values := row.take() >>> (err) {
println(err.msg())
<< 1
}
println("selected=" + (values[0] as string))
db.close() >>> (err) {
println(err.msg())
<< 1
}
<< 0
}35_standalone_mysql/main.xu@main
mysql #github.com/xulang-org/packages/mysql
#database/sql/driver
#context
fn verify_mysql_live() {
println("--- Testing Native MySQL/MariaDB Driver Wire Protocol ---")
dsn := "root:root@tcp(127.0.0.1:3306)/xu_demo?tls=false"
$conn := mysql.open(dsn)
// 1. Ping
err := conn.ping()
if err.len > 0 {
println(" [FAIL] Ping failed: " + err)
conn.close()
<<
}
println(" [PASS] MySQL/MariaDB Ping succeeded.")
// 2. Exec DDL
r1 := conn.exec("DROP TABLE IF EXISTS xu_developers;", []driver.NamedValue{})
if r1.err.len > 0 {
println(" [FAIL] Drop table error: " + r1.err)
conn.close()
<<
}
r2 := conn.exec("CREATE TABLE xu_developers (id INT PRIMARY KEY, name VARCHAR(50), commits INT);", []driver.NamedValue{})
if r2.err.len > 0 {
println(" [FAIL] Create table error: " + r2.err)
conn.close()
<<
}
println(" [PASS] Table 'xu_developers' created.")
// 3. Exec DML Insert
$args1 := []driver.NamedValue{}
args1.push(driver.NamedValue{ordinal: 1, name: "", value: 1})
args1.push(driver.NamedValue{ordinal: 2, name: "", value: "Antigravity"})
args1.push(driver.NamedValue{ordinal: 3, name: "", value: 500})
r3 := conn.exec("INSERT INTO xu_developers (id, name, commits) VALUES (?, ?, ?);", args1)
if r3.err.len > 0 {
println(" [FAIL] Insert error: " + r3.err)
conn.close()
<<
}
println(" [PASS] Developer inserted (rows=" + str(r3.rows_affected) + ").")
// 4. Query
$q_args := []driver.NamedValue{}
q_args.push(driver.NamedValue{ordinal: 1, name: "", value: 1})
rows := conn.query("SELECT id, name, commits FROM xu_developers WHERE id = ?;", q_args)
if rows.err.len > 0 {
println(" [FAIL] Query error: " + rows.err)
conn.close()
<<
}
println(" [PASS] Query executed, columns count: " + str(rows.columns.len))
$i := 0
while i < rows.columns.len {
println(" Col[" + str(i) + "]: " + rows.columns[i])
i = i + 1
}
println(" Total cells retrieved: " + str(rows.cells.len))
$j := 0
while j < rows.cells.len {
println(" Cell[" + str(j) + "]: " + rows.cells[j])
j = j + 1
}
// 5. Transaction
println(" Testing Transaction Commit...")
$tx := conn.begin()
$args2 := []driver.NamedValue{}
args2.push(driver.NamedValue{ordinal: 1, name: "", value: 2})
args2.push(driver.NamedValue{ordinal: 2, name: "", value: "XuArchitect"})
args2.push(driver.NamedValue{ordinal: 3, name: "", value: 1000})
tx_res := conn.exec("INSERT INTO xu_developers (id, name, commits) VALUES (?, ?, ?);", args2)
if tx_res.err.len > 0 {
println(" [FAIL] Tx insert error: " + tx_res.err)
}
tx_err := tx.commit()
if tx_err.len > 0 {
println(" [FAIL] Tx commit error: " + tx_err)
} else {
println(" [PASS] Transaction committed.")
}
// 6. Reset session
ctx := context.background()
reset_err := conn.reset_session(&ctx)
if reset_err.len > 0 {
println(" [FAIL] Reset session error: " + reset_err)
} else {
println(" [PASS] Reset session completed.")
}
// 7. Close
close_err := conn.close()
if close_err.len > 0 {
println(" [FAIL] Close error: " + close_err)
} else {
println(" [PASS] Connection closed cleanly.")
}
}
fn verify_mysql_pool() {
println("\n--- Testing Native MySQL/MariaDB Connection Pool ---")
dsn := "root:root@tcp(127.0.0.1:3306)/xu_demo?tls=false"
$pool := mysql.open_pool(dsn + "", 5, 2)
pool.ping() >>> (err) {
println(" [FAIL] Pool ping error: " + err.msg())
<<
}
println(" [PASS] MySQL Pool ping succeeded.")
// 1. DDL
pool.exec("DROP TABLE IF EXISTS xu_pool_orders;") >>> (err) {
println(" [FAIL] Drop table error: " + err.msg())
<<
}
pool.exec("CREATE TABLE xu_pool_orders (id INT PRIMARY KEY, title VARCHAR(50), amount INT);") >>> (err) {
println(" [FAIL] Create table error: " + err.msg())
<<
}
println(" [PASS] Pool created table xu_pool_orders.")
// 2. Concurrency / multiple inserts
$i := 1
while i <= 5 {
pool.exec("INSERT INTO xu_pool_orders (id, title, amount) VALUES (?, ?, ?);", i, "Order_" + str(i), i * 150) >>> (err) {
println(" [FAIL] Insert row error: " + err.msg())
<<
}
i = i + 1
}
println(" [PASS] Concurrently inserted 5 rows across pooled connections.")
// 3. Query
$rows := pool.query("SELECT id, title, amount FROM xu_pool_orders ORDER BY id;") >>> (err) {
println(" [FAIL] Pool query error: " + err.msg())
<<
}
$count := 0
while rows.next() {
vals := rows.take() >>> (err) {
println(" [FAIL] rows.take error: " + err.msg())
<<
}
oid := vals[0] as int
otitle := vals[1] as string
oamt := vals[2] as int
println(" Row[" + str(count) + "]: id=" + str(oid) + ", title=" + otitle + ", amount=" + str(oamt))
count = count + 1
}
rows.close()
if count == 5 {
println(" [PASS] Pool query verified 5 rows.")
} else {
println(" [FAIL] Row count mismatch: " + str(count))
}
// 4. Transaction via Pool
$tx := pool.begin() >>> (err) {
println(" [FAIL] Pool begin tx error: " + err.msg())
<<
}
tx.exec("INSERT INTO xu_pool_orders (id, title, amount) VALUES (?, ?, ?);", 6, "Order_6", 900) >>> (err) {
println(" [FAIL] Tx insert error: " + err.msg())
<<
}
tx.commit() >>> (err) {
println(" [FAIL] Tx commit error: " + err.msg())
<<
}
println(" [PASS] Transaction committed via pool.")
// 5. Cleanup & Close
pool.exec("DROP TABLE IF EXISTS xu_pool_orders;") >>> (err) {
println(" [FAIL] Cleanup table error: " + err.msg())
<<
}
pool.close() >>> (err) {
println(" [FAIL] Pool close error: " + err.msg())
<<
}
println(" [PASS] MySQL Pool closed cleanly.")
}
fn main() {
println("=== Xu MySQL / MariaDB Native Driver Verification ===\n")
verify_mysql_live()
verify_mysql_pool()
println("\n[MYSQL VERIFICATION 100% COMPLETED]")
}driverpub fn driver() driver.DriverReturn the database driver instance implementing driver.Driver.
No arguments are required.
driver.Driver — a value of this type
openpub fn open(dsn string) driver.ConnOpen resource or establish connection.
dsn stringdriver.Conn — a value of this type
struct Configpub struct Config {
pub host string
pub port int
pub user string
pub password string
pub database string
pub tls_mode string
pub root_cert_file string
}Mysql Configuration parameters and options set.
host stringport intuser stringpassword stringdatabase stringtls_mode stringroot_cert_file stringnew_configpub fn new_config() ConfigConstruct config.
No arguments are required.
Config — a value of this type
parse_dsnpub fn parse_dsn(dsn string) ConfigParse as dsn. Throws on failure; handle the error or propagate it to the caller.
dsn stringConfig — a value of this type
struct MysqlDriverpub struct MysqlDriver {
pub tag int
pub dsn string
}Structure encapsulating tag, dsn.
tag intdsn stringopen_dbpub fn open_db(dsn string) sql.DBOpen db.
dsn stringsql.DB — a value of this type
open_poolpub fn open_pool(dsn string, max_open int, max_idle int) sql.DBOpen pool.
dsn stringmax_open intmax_idle intsql.DB — a value of this type
struct TlsClientpub struct TlsClient {
pub conn transport.Conn
pub host string
pub port int
}Mysql Client session maintaining connection and operations.
conn transport.Connhost stringport inttls_connectpub fn tls_connect(endpoint string, default_port int) TlsClientTls connect. Throws on failure; handle the error or propagate it to the caller.
endpoint stringdefault_port intTlsClient — a value of this type
tls_connect_configpub fn tls_connect_config(endpoint string, default_port int, cfg tls.Config) TlsClientTls connect config. Throws on failure; handle the error or propagate it to the caller.
endpoint stringdefault_port intcfg tls.ConfigTlsClient — a value of this type
($&TlsClient) write_allpub fn (c $&TlsClient) write_all(data string) intOperation on $&TlsClient: write all. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).data stringint — a value of this type
($&TlsClient) readpub fn (c $&TlsClient) read(max int) stringOperation on $&TlsClient: read up to max bytes. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).max intstring — result string
($&TlsClient) read_exactpub fn (c $&TlsClient) read_exact(need int) stringOperation on $&TlsClient: read exact. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).need intstring — result string
($&TlsClient) closepub fn (c $&TlsClient) close() intOperation on $&TlsClient: close the resource. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).int — a value of this type
($&TlsClient) set_deadlinepub fn (c $&TlsClient) set_deadline(t_ns int) intOperation on $&TlsClient: set deadline. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).t_ns intint — a value of this type
($&TlsClient) set_read_deadlinepub fn (c $&TlsClient) set_read_deadline(t_ns int) intOperation on $&TlsClient: set read deadline. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).t_ns intint — a value of this type
($&TlsClient) set_write_deadlinepub fn (c $&TlsClient) set_write_deadline(t_ns int) intOperation on $&TlsClient: set write deadline. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).t_ns intint — a value of this type