🤖 Ai回答: To connect to a MySQL database using Dart, you can use the `mysql1` package (the most popular and maintained solution for server-side Dart applications)、Here's a step-by-step guide:
1、Add Dependency
Add `mysql1` to your `pubspec.yaml`:
yaml
dependencies:
mysql1: ^0.18.0
Run `dart pub get` to install it.
2、Basic Connection Example
dart
import 'package:mysql1/mysql1.dart';
void main() async {
try {
// Connect to MySQL
final connection = await MysqlConnection.connect(ConnectionSettings(
host: 'localhost',
port: 3306,
user: 'root',
password: 'your_password',
db: 'your_database',
// Optional: SSL, timeout, etc.
));
// Execute a query
final results = await connection.query('SELECT * FROM users');
for (var row in results) {
print('ID: ${row['id']}, Name: ${row['name']}');
}
// Close the connection
await connection.close();
} catch (e) {
print('Error: $e');
}
}
3、Key Details
Async/Await: All database operations are `async` (use `await` or `then`).
Connection Settings:
`host`: Database server (e.g., `localhost` or `127.0.0.1`).
`port`: Default MySQL port is `3306`.
`user`/`password`: Your MySQL credentials.
`db`: Target database name.
Security: Never hardcode credentials in source code、Use environment variables (e.g., `dotenv` package) or a secure config manager.
4、Best Practices
Close Connections: Always `await connection.close()` after use to prevent leaks.
Error Handling: Wrap operations in `try/catch` blocks.
Prepared Statements: Use for security (prevents SQL injection):
dart
final result = await connection.query(
'SELECT * FROM users WHERE id = ?',
[123],
);
Transactions: Use `connection.beginTransaction()` and `connection.commit()` for critical operations.
5、Important Notes
Not for Flutter Apps: Direct MySQL access from client-side Flutter apps is not recommended due to:
Security risks (exposing credentials).
Network latency (mobile apps shouldn't connect directly to databases).
Solution: Use a Dart server (e.g., with `http` package) as a backend API for Flutter.
Server-Side Only: This approach is for Dart server applications (e.g., running on a cloud server like AWS).
6、Debugging Tips
If connection fails:
Check if MySQL server is running.
Verify firewall rules (e.g., port `3306` is open).
Ensure credentials are correct (test with `mysql -u root -p`).
Use `ConnectionSettings` parameters like `timeout` to handle slow networks.
Alternative Package (Less Common)
`mysql_client`: A newer but less mature package、Use `mysql1` for stability.
Example: Insert Data
dart
final result = await connection.query(
'INSERT INTO users (name, email) VALUES (?, ?)',
['John Doe', 'john@65.hk'],
);
print('Inserted ID: ${result.lastInsertId}');
This setup is ideal for Dart backend services (e.g., APIs, microservices) that need to interact with MySQL、For mobile apps, always use a separate backend service (e.g., a Dart/Flutter server) to handle database operations securely.