0

I want to insert 2 QString to my database but I face this error:

QSqlError(1, "Unable to execute statement", "table login_t already exists")

and my database is empty my code is:

void School::set_db( QString usern, QString pass )
{
    QSqlDatabase db1 =QSqlDatabase::addDatabase("QSQLITE");
    db1.setDatabaseName( "school1.db");
    bool isOpen = db1.open() ;
    QSqlQuery q(db1);
    QString queryString = "INSERT INTO login_t (user, pass) VALUES (?,?)";
    q(queryString);
    q.addBindValue(usern);
    q.addBindValue(pass);
    q.exec();
}
set_db("user1" , "pass1");

I make my database and tables before.

2 Answers 2

1

According with your message of error table login_t already exists, i can tell, you try create table login_t while this table already exist. (You should try create empty DB (without tables) and when you fix prepare statement, run your code again)

Other hand, if you create DB and tables before run your code, you need fix prepare statement in query only. (don't forget, dataBaseName takes full path to your DB. If you write school.db, it will be search your DB file near bin file)

Sign up to request clarification or add additional context in comments.

Comments

0

Make sure the database was correctly created. You can use external tools like SQLite Studio to do so. You can also try to "recreated" the entire database and check if the issue was fixed.

Check out the code below:

bool School::set_db(QString usern, QString pass)
{
    QSqlDatabase db1 = QSqlDatabase::addDatabase("QSQLITE");

    // You need to set the full path to the database file. E.g.: "C:/Databases/school1.db"
    db1.setDatabaseName("school1.db");

    if( !db1.open() )
    {
        qDebug() << "Could not open the database connection!";
        qDebug() << "Error:" << db1.lastError();
        return false;
    }

    QSqlQuery query(db1);
    QString queryString = "INSERT INTO login_t (user, pass) VALUES (:user, :pass)";

    if( !query.prepare(queryString) )
    {
        qDebug() << "Prepare:" << query.lastError();
        return false;
    }

    query.addBindValue(":user", usern);
    query.addBindValue(":pass", pass);

    if( !query.exec() )
    {
        qDebug() << "Exec:" << query.lastError();
        return false;
    }

    return true;
}

set_db("user1", "pass1");

I'm not sure, but the error message that you showed seems to be printed in another block of code. Maybe in some place that you are trying to create the login_t table.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.