You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

QString引号使用错误:Qt中SQLite密码找回功能代码求助

Fixing QString Quote Issues in Qt SQLite Password Recovery

Hey there! Let's tackle that quote problem you're hitting with your password recovery code. From what you shared, the issue is likely tied to how you're constructing your SQL query string—either unclosed quotes, improper string concatenation, or not handling user input safely. Here's how to fix it step by step:

Common Causes of the Quote Error

  • Unclosed string literal: If your SQL query cuts off mid-string (like your SELECT username,password,s... snippet), the compiler will throw an error because it can't find the closing " for your QString.
  • Directly concatenating user input: If you tried to splice the username variable into your SQL string like QString qstr = "SELECT password FROM users WHERE username = " + username;, you'll hit quote issues because the username value isn't wrapped in single quotes (required for SQL string values), and if the username contains special characters (like '), it'll break the query entirely.

The Safe & Correct Solution

Instead of manually handling quotes, use Qt's parameter binding with QSqlQuery—this avoids quote headaches and protects against SQL injection attacks (a critical security issue for user input). Here's the revised code:

// Get username input from user
QString username = QInputDialog::getText(
    this, 
    "Password Recovery", 
    "Please enter your username here:", 
    QLineEdit::Normal,
    "", // Empty default instead of hardcoded "myUsername"
    Q_NULLPTR, 
    Qt::WindowFlags(), 
    Qt::ImhNone
);

// Check if user canceled the input dialog
if (username.isEmpty()) {
    return; // Exit early if no username was entered
}

// Handle SQLite database connection (avoid duplicate connections!)
QSqlDatabase db;
if (QSqlDatabase::contains("recoveryConn")) {
    db = QSqlDatabase::database("recoveryConn");
} else {
    db = QSqlDatabase::addDatabase("QSQLITE", "recoveryConn");
    db.setDatabaseName("/home/arian_press/Qt5.7.0/Projects/APQt_chat/apt.db");
}

if (db.open()) {
    QSqlQuery query(db); // Pass the database connection to the query
    // Use a placeholder (:username) instead of concatenating the value
    QString qstr = "SELECT password FROM your_table_name WHERE username = :username";
    
    if (query.prepare(qstr)) {
        // Bind the username value to the placeholder
        query.bindValue(":username", username);
        
        if (query.exec()) {
            // Check if a matching user was found
            if (query.next()) {
                QString retrievedPassword = query.value(0).toString();
                // Do something with the password (e.g., show it to the user securely)
                QMessageBox::information(this, "Success", "Your password is: " + retrievedPassword);
            } else {
                QMessageBox::warning(this, "Error", "Username not found!");
            }
        } else {
            qDebug() << "Query execution failed:" << query.lastError().text();
        }
    } else {
        qDebug() << "Query preparation failed:" << query.lastError().text();
    }
    
    db.close();
} else {
    qDebug() << "Failed to open database:" << db.lastError().text();
}

Key Improvements Explained

  1. Parameter Binding: Using :username as a placeholder and bindValue() ensures the username is properly escaped, eliminating quote errors and SQL injection risks.
  2. Database Connection Management: Checks for an existing connection before creating a new one—Qt can throw errors if you call addDatabase() multiple times with the same driver name.
  3. Input Validation: Exits early if the user cancels the input dialog, avoiding unnecessary database operations.
  4. Error Handling: Adds debug output for database/query errors to help you troubleshoot if something goes wrong.

Make sure to replace your_table_name with the actual name of your SQLite table that stores usernames and passwords!

内容的提问来源于stack exchange,提问作者comp94 ui

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:31:30