includebrainh
includebrainh

Reputation: 143

SQLite CREATE query in QT

dataBase = QSqlDatabase::addDatabase("QSQLITE");
dataBase.setDatabaseName("login_password.sqlite");

QSqlQuery authQuery;

if(!dataBase.open())
{
    qDebug() << dataBase.lastError().text();
}

QString create("CREATE TABLE BASE(LOGIN VARCHAR(15) PRIMARY KEY NOT NULL, "
               "PASSWRD TEXT(50) NOT NULL, RIGHTS INT NOT NULL);");

bool state = authQuery.exec(create);
if(!state) qDebug() << "Не удалось создать таблицу!";

What's wrong with query and is it possible to make text PRIMARY KEY?

Upvotes: 0

Views: 666

Answers (1)

Mike
Mike

Reputation: 8355

From the docs:

Warning: You must load the SQL driver and open the connection before a QSqlQuery is created. Also, the connection must remain open while the query exists; otherwise, the behavior of QSqlQuery is undefined.

In your question, you are creating the QSqlQuery before opening the database, you have to move the authQuery declaration statement after the dataBase.open() call, like this:

QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("login_password.sqlite");
if (!db.open())
    qDebug() << "error opening database: " << dataBase.lastError().text();

QSqlQuery authQuery;
QString create("CREATE TABLE BASE(LOGIN VARCHAR(15) PRIMARY KEY NOT NULL, "
               "PASSWRD TEXT(50) NOT NULL, RIGHTS INT NOT NULL);");
if(!authQuery.exec(create)){
    qDebug() << "error executing statement: " << authQuery.lastError().databaseText();
}

Upvotes: 2

Related Questions