Flutter(Mac环境)从MySQL读取数据失败排查求助
Hey there! Let's break down why your query isn't populating the name variable as expected, even though the same SQL works in MySQL Workbench. Here are the key fixes and checks to try:
1. Add Error Handling to Catch Hidden Issues
Right now your code doesn't handle errors, so you might be missing connection or query failures that are silently breaking things. Update your _getname function to include error catching:
void _getname() { db.getConnection().then((conn) { String sql = 'select `name` from `userstable` where id = 20;'; conn.query(sql).then((results) { // Debug: Check how many rows were returned print('Query returned ${results.length} rows'); if (results.isNotEmpty) { var fetchedName = results.first[0]; print('Fetched name: $fetchedName'); // Verify the value exists setState(() { name = fetchedName; }); } else { print('No matching record found for id=20'); } // Critical: Close the connection to avoid leaks conn.close(); }).catchError((error) { print('Query failed: $error'); conn.close(); }); }).catchError((error) { print('Database connection failed: $error'); }); }
2. Verify Your Connection & Query Context
Even if your insert works, double-check these details:
- Database Matching: Ensure the
users_test_MACdatabase in yourMysqlclass is the exact same one you're querying in Workbench. - Record Existence: Confirm the
userstableactually has a row withid=20(typos in IDs or table names are easy to miss!). - Character Set: Add a charset parameter to your
ConnectionSettingsto avoid encoding mismatches that can hide results:var settings = new ConnectionSettings( host: host, port: port, user: user, password: password, db: db, charset: 'utf8mb4' // Match your database's charset );
3. Optimize State Management
Your original loop calls setState for every row (unnecessary for a single result). The updated code above grabs the first result directly and only calls setState once, which is more efficient and reduces potential context issues.
4. Don’t Forget to Close Connections
Leaving database connections open can lead to resource leaks over time. Always call conn.close() after your query completes (even if there’s an error) to clean up.
Next Steps
Run the updated code and check your debug console:
- If you see "Query returned 0 rows", double-check your SQL condition and database table.
- If you see an error message, it will point directly to the problem (e.g., permission issues, incorrect credentials).
- If you see the fetched name printed but
namestill doesn’t update, confirm_getnameis being called from a validStatefulWidgetcontext.
内容的提问来源于stack exchange,提问作者justin

