MySQL Connector C++中PreparedStatement的setString方法失效问题
It looks like you're trying to fetch a Gebruiker record by matching login credentials, but hitting a roadblock with the setString method of PreparedStatement. Let's walk through the most common fixes for this problem:
Double-check parameter indexing
MySQL Connector C++ uses 1-based indexing for prepared statement parameters. Your SQL query has two placeholders (?), so make sure you're binding them correctly:prep_stmt->setString(1, login); // Binds to the first ? (Gebruiker_login) prep_stmt->setString(2, wachtwoord); // Binds to the second ? (Gebruiker_wachtwoord)Accidentally using 0-based indexing is a super common mistake that breaks parameter binding silently.
Fix character encoding mismatches
Since your table and field names use Dutch language characters, there's a good chance encoding mismatches are causing values to not match. First, ensure your connection uses a compatible charset (likeutf8mb4to cover all special characters):dbConn->getConnection()->setClientOption("charset", "utf8mb4");Also verify that the
Gebruiker_loginandGebruiker_wachtwoordcolumns in your database are set toutf8mb4charset and collation (e.g.,utf8mb4_general_ci).Add detailed error logging
Your current code has atryblock but no error handling. Catchsql::SQLExceptionto get precise error details—this will tell you exactly if the issue is with binding, permissions, or invalid SQL:catch (sql::SQLException &e) { std::cerr << "SQL Error Message: " << e.what() << std::endl; std::cerr << "MySQL Error Code: " << e.getErrorCode() << std::endl; std::cerr << "SQL State: " << e.getSQLState() << std::endl; // Clean up resources before returning delete res; delete prep_stmt; return nullptr; }Ensure proper query execution and result handling
Don't forget to execute the query and move the result set pointer to access the returned row:res = prep_stmt->executeQuery(); if (res->next()) { // Populate your Gebruiker object with data from the result set gebruiker = new Gebruiker(); gebruiker->setLogin(res->getString("Gebruiker_login")); // Add other field assignments here } // Always clean up resources to avoid leaks delete res; delete prep_stmt;Skipping
executeQuery()orres->next()will make it look likesetStringfailed, when in reality the query never ran or you didn't check the results.Verify password storage logic
If yourGebruiker_wachtwoordcolumn stores hashed passwords (e.g., bcrypt, SHA-256), you can't bind the plaintextwachtwoorddirectly. You need to hash the input password using the same algorithm first, then bind the hashed value to the statement.
内容的提问来源于stack exchange,提问作者DerDerrr




