How to Connect Dart and Flutter to SQL Server Using mssql_native
Connect Flutter and Dart to Microsoft SQL Server using a native FreeTDS driver. Learn authentication, connection pooling, transactions, bulk insert, and streaming.
Using SQL Server in Dart and Flutter
Flutter is used on the desktop (especially Windows), on mobile, and on handheld terminals for internal systems such as ERP, warehouse automation, and logistics. We prefer not to embed database details in code, but sometimes we still have to. Or we write Dart on the server as well, with packages such as Dart Frog, Relic, and Serverpod, and build our backend on Dart. A few packages talk to Microsoft SQL Server directly, but they are not stable.
Until now, the choice was either to put a small REST service written in .NET or Node.js in between and pay the extra infrastructure cost and network latency, or to struggle with fragile packages that require installing freetds.dll or ODBC on the operating system by hand.
With mssql_native, we can solve these problems without the hassle.
1. Setup with Dart native assets
mssql_native is built on FreeTDS, the open source library that implements the TDS protocol. You do not need to install a C compiler on the operating system or point to a DLL path with environment variables.
Thanks to Dart’s Native Assets (Build Hooks), when you run flutter run, flutter build, or dart build cli, native binary files for the target platform (Windows, Linux, macOS, iOS, or Android) are linked in.
dependencies:
mssql_native: ^0.2.0The native C library starts once for the whole process. If you are using Flutter, start the engine in `main()` after `WidgetsFlutterBinding`. If you are writing a CLI or a backend, start it at the very beginning:
import 'package:mssql_native/mssql_native.dart';
Future<void> main() async {
// 1. Start the engine
await MssqlRuntime.instance.initialize();
try {
// Application flow...
} finally {
// 2. Release resources on shutdown
await MssqlRuntime.instance.shutdown();
}
}2. Connections and enterprise authentication
In enterprise environments, SQL Server usually runs on the company’s internal Active Directory (domain). It asks for the Windows session instead of a SQL username and password. The package supports these cases:
// Standard username and password connection
final conn = await MssqlConnection.connect(
host: '192.168.1.50',
database: 'CompanyDB',
username: 'sa',
password: 'Password123!',
options: const MssqlConnectionOptions(
loginTimeout: Duration(seconds: 10),
queryTimeout: Duration(seconds: 30),
),
);
// Passwordless on Windows, as the current Windows user (SSPI)
final sspiConn = await MssqlConnection.connectIntegrated(
host: 'sqlserver.corp.local',
database: 'FinanceDB',
);
// Parse an existing .NET connection string directly
final connStr = await MssqlConnection.connectString(
'Server=sqlserver.corp.local;Database=FinanceDB;Trusted_Connection=True;',
);Note: If you want to connect from a non-Windows system (Linux, macOS, Android) as an Active Directory domain user, NTLMv2 is also supported with `username: ‘CORP\\app’`.
3. Parameterized queries and type safety
To cut the risk of SQL injection, parameters go to the server as a separate packet from the query body. Returned data is read with `queryRows`, `querySingle`, `queryScalar`, and `queryTypedRows`.
Floating-point drift and MssqlDecimal
Other MSSQL packages convert SQL Server `DECIMAL`, `NUMERIC`, or `MONEY` values directly to the Dart `double` type. Rounding caused by the binary format (IEEE 754) produces kuruş differences in accounting and balance calculations. The package has an `MssqlDecimal` type that does base-10 arithmetic for this reason.
// 1. queryScalar: for reading a single value (e.g. COUNT, SUM, or ID)
final totalOrders = await conn.queryScalar<int>(
'SELECT COUNT(*) FROM dbo.orders WHERE status = @status',
parameters: {'status': 'pending'},
);
// 2. queryTypedRows: type-safe reads with null checks
final rows = await conn.queryTypedRows(
'''
SELECT id, product_code, price, stock_count, created_at
FROM dbo.products
WHERE category_id = @catId
''',
parameters: {'catId': 42},
);
for (final row in rows) {
final int id = row.require<int>('id');
final String code = row.require<String>('product_code');
final int stock = row.require<int>('stock_count');
// An exact decimal that never produces a floating-point error:
final MssqlDecimal price = row.require<MssqlDecimal>('price');
// get<T> for fields that can be null:
final DateTime? createdAt = row.get<DateTime>('created_at');
print('Product #$id: $code - $price ₺');
}4. Concurrency: connection pooling
Two separate TDS queries cannot run at the same time over a single physical TCP socket. A connection pool is required on the server side (Serverpod, Dart Frog, Relic) or on Flutter screens that fetch data at the same time.
`MssqlConnectionPool` works on a connection leasing model, keeps the connections alive, and spreads the load:
final pool = MssqlConnectionPool(
MssqlConnectionConfig(
host: 'db.example.com',
database: 'ERP',
username: 'app_user',
password: 'secure_password',
),
poolConfig: const MssqlPoolConfig(
minimumSize: 2, // Connections kept ready while idle
maximumSize: 10, // Ceiling that can be reached when needed
acquireTimeout: Duration(seconds: 5),
),
);
// Bring up the minimum connections at startup
await pool.warmUp();
// Usage 1: a one-off query (takes a connection from the pool, runs, and returns it immediately)
final customers = await pool.session.queryRows('SELECT * FROM dbo.customers');
// Usage 2: hold the same connection and run sequential work (transaction / temp table)
await pool.withConnection((conn) async {
await conn.execute('CREATE TABLE #temp (id INT)');
await conn.execute('INSERT INTO #temp VALUES (10)');
final count = await conn.queryScalar<int>('SELECT COUNT(*) FROM #temp');
print('Rows in the temp table: $count');
});5. Large data: streaming and cancellation (ATTN packet)
If a user leaves the page while pulling a large report, or the screen locks on a mobile device, stopping listening to the `Future` on the Dart side does not stop the query on SQL Server. The database keeps consuming CPU in the background.
Get Ökkeş Aksoy’s stories in your inbox
Join Medium for free to get updates from this writer.
`mssql_native` sends the cancellation request to SQL Server as an ATTN (Attention) signal in the TDS protocol, and the server cuts the query off and terminates the operation:
final cancelToken = MssqlCancellationToken();
// For example, if the user presses Cancel in the UI:
void onUserCancel() {
cancelToken.cancel('The user stopped the operation midway');
}
try {
// Stream 500,000 rows in batches of 1,000 without inflating memory
final rowStream = conn.streamRows(
'SELECT * FROM dbo.audit_logs WHERE created_at >= @date',
parameters: {'date': DateTime(2025, 1, 1)},
options: const MssqlQueryOptions(batchRows: 1000),
cancellationToken: cancelToken,
);
await for (final row in rowStream) {
// Write to disk or a file without running out of memory (OOM)
await writeToDisk(row);
}
} on MssqlCancelledException {
print('The query was stopped in the database engine and resources were released.');
}6. Transactions and savepoints
When a nested step fails, you can continue without rolling back the main operation. A SQL Server savepoint separates the nested step from the main operation:
await conn.transaction((tx) async {
// 1. Main balance deduction
await tx.execute(
'UPDATE dbo.wallets SET balance = balance - 100 WHERE user_id = @uid',
parameters: {'uid': 1},
);
try {
// 2. Nested step: logging (savepoint)
await tx.savepoint(() async {
await tx.execute('INSERT INTO dbo.activity_logs (message) VALUES (@msg)',
parameters: {'msg': 'Payment received'});
});
} on MssqlException {
// Even if the write to the log table fails, the savepoint is rolled back;
// the wallet debit is not cancelled!
print('The log could not be written, but the flow was not broken.');
}
// The transaction is committed successfully.
}, isolationLevel: MssqlIsolationLevel.readCommitted);7. High-volume transfer: bulk insert and stored procedures (TVP)
Bulk insert
Sending thousands of rows with individual `INSERT` statements means a network round trip for every row. On large transfers this takes hours. `bulkInsert` writes the data to the server in seconds, using the TDS protocol’s Bulk Copy feature:
// A lazy/generator data source that does not consume memory
Iterable<Map<String, Object?>> generateMetrics() sync* {
for (var i = 0; i < 50000; i++) {
yield {
'device_id': 'DEV_$i',
'temperature': 24.5,
'recorded_at': DateTime.now(),
};
}
}
final result = await conn.bulkInsert(
tableName: 'dbo.device_telemetry',
rows: generateMetrics(),
options: const MssqlBulkOptions(
batchSize: 5000,
mode: MssqlBulkMode.batched, // If there is an error, processed batches are kept
tableLock: true, // Locks the target table for higher speed
),
onProgress: (sent) => print('$sent rows transferred...'),
);
print('${result.insertedRows} rows were written in ${result.elapsed.inMilliseconds} ms.');Table-valued parameters (TVP) and stored procedures
TVP is used to send a list or a table in a single procedure call:
final spResult = await conn.callProcedure(
'dbo.create_order_with_items',
parameters: {
'customer_id': 1001,
// Send a table-valued type to the server in one go:
'order_items': MssqlTableRows([
{'product_id': 10, 'qty': 2, 'unit_price': 150.0},
{'product_id': 15, 'qty': 1, 'unit_price': 300.0},
]),
},
// Capture the output parameter produced by the procedure:
outputParameters: {'generated_order_id'},
);
final orderId = spResult.outputParameters['generated_order_id'];
print('Created order no: $orderId');8. Logs, error types, and APM
When `mssql_native` throws, it does not write the SQL query text or the parameters to the log. A user password, or data covered by KVKK, cannot end up in Datadog or Sentry. You can tag queries with `queryName: ‘getUserByEmail’`.
Typed errors are caught instead of text matching such as `error.message.contains(“UNIQUE”)`:
try {
await conn.execute(
'INSERT INTO dbo.users (email) VALUES (@email)',
parameters: {'email': 'test@example.com'},
);
} on MssqlConstraintException catch (e) {
if (e.isDuplicateKey) {
print('This email address is already registered.');
}
} on MssqlQueryTimeoutException {
print('The query did not finish within the allotted time.');
}OpenTelemetry / APM (`MssqlObserver`)
You can attach your own observer class without taking on a heavy package dependency from outside:
class MyDatabaseObserver extends MssqlObserver {
@override
void onQueryStart(MssqlQueryContext context) {
// Start a Datadog / OpenTelemetry span
}
@override
void onQueryComplete(MssqlQueryContext context, Duration elapsed, Object? error) {
if (elapsed > const Duration(seconds: 1)) {
print('Slow query warning: ${context.queryName ?? "Unnamed"} ($elapsed)');
}
}
}
// Added to the connection or the pool:
final conn = await MssqlConnection.connect(
// ...
options: MssqlConnectionOptions(observer: MyDatabaseObserver()),
);And many more usage examples are available.
Driver and ORM layer
`mssql_native` is the driver for the ORM layer above it. Writing model classes by hand takes a long time on a database with more than 100 tables, so the system is split into three layers:
- mssql_native: the C/FFI driver layer that runs at the TDS protocol level.
- mssql_orm: a type-safe query builder and the database-first ORM runtime.
- mssql_orm_dev: a CLI tool that reads your existing SQL Server schema and generates Dart classes and their relations.
While working with ORM models, you can call raw SQL or a stored procedure through mssql_native inside the same transaction, for a step that needs the performance.
Package
`mssql_native` was written so Dart and Flutter can connect to SQL Server without an extra installation.
- pub.dev: https://pub.dev/packages/mssql_native
- GitHub: https://github.com/Aksoyhlc/mssql_native
For a question, a suggestion, or a scenario you run into, write in the comments or on GitHub.








