I can't Insert a new data to SQLITE



  • I tried to insert new data to the database. here's my code:
    @#include "mainwindow.h"
    #include <QtSql/QSqlDatabase>
    #include <QtDebug>
    #include <QtGui/QApplication>
    #include <QtSql>

    int main(int argc, char *argv[])
    {
    QApplication app(argc, argv);

    //MainWindow mainWindow;
    //mainWindow.setOrientation(MainWindow::ScreenOrientationAuto);
    //mainWindow.showExpanded();
    
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("C:\sqlite3\sample1.db");
    
    if(!db.open())
    {
        qFatal("Failed to connect!");
    }
    
    else
    
    qDebug("Connected.");
    
    QSqlQuery qry;
    
    qry.prepare("insert into sample1.db (firstname, lastname) values ('John','Dean')");
    if (!qry.exec&#40;&#41;)
    
        qDebug() << qry.lastError();
    
    else
      qDebug("Inserted");
    
    
    db.close();
    return 0;
    
    return app.exec();
    

    }
    @

    It has no errors but when I look into my sqlite using SELECT statement to see if it works, nothings happened the data that I want to add is not there.

    thanks in advance!



  • Hi,

    You should create table in the database and then to insert values into the table. Test your queries with SQlite command line tool such as sqlite3.exe before adding them to the source code.

    Cheers,
    Leon



  • I think your database name is invalid. Remember, a backslash is used for escaping in C++ strings... It is good practice to only use backslashes for the display of paths on platforms where a backslash is the path separator (you do that translation using QDir::toNativeSeparators). In your own code, use forward slashes only.



  • Hi again,

    I just want to post several useful links which will solve the issue:
    "CREATE TABLE":http://www.sqlite.org/lang_createtable.html
    Examples:
    "Creating an SQLite database in Qt":http://wiki.forum.nokia.com/index.php/CS001504_-Creating_an_SQLite_database_in_Qt
    "Creating a database table in Qt":http://wiki.forum.nokia.com/index.php/CS001505
    -Creating_a_database_table_in_Qt
    "Inserting a row into a database in Qt":http://wiki.forum.nokia.com/index.php/CS001506
    -_Inserting_a_row_into_a_database_in_Qt

    Follow the examples in the order I have posted them, merge them into a single application and you will solve the issues.



  • thanks to both of you! now I modified the code. but still nothing happened.

    here's the code:
    @#include "mainwindow.h"
    #include <QtSql/QSqlDatabase>
    #include <QtDebug>
    #include <QtGui/QApplication>
    #include <QtSql>

    int main(int argc, char *argv[])
    {
    QApplication app(argc, argv);

    //MainWindow mainWindow;
    //mainWindow.setOrientation(MainWindow::ScreenOrientationAuto);
    //mainWindow.showExpanded();
    
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("C:/sqlite3/sample1.db");
    
    if(!db.open())
    {
        qFatal("Failed to connect!");
    }
    
    else
    
    qDebug("Connected.");
    
    QSqlQuery qry;
    
    qry.prepare( "CREATE TABLE IF NOT EXISTS names (id INTEGER UNIQUE PRIMARY KEY, firstname VARCHAR(30), lastname VARCHAR(30))" );
      if( !qry.exec&#40;&#41; )
        qDebug() << qry.lastError();
      else
        qDebug() << "Table created!";
    
    qry.prepare("insert into names (id, firstname, lastname) values (1, 'John','Dean')");
    if (!qry.exec&#40;&#41;)
    
        qDebug() << qry.lastError();
    
    else
      qDebug("Inserted");
    
    
    db.close();
    return 0;
    
    return app.exec();
    

    }
    @

    is there something in the code that i have to replace?



  • [quote author="wenks21" date="1305614955"]is there something in the code that i have to replace?[/quote]

    Have you tested your SQL statements only using the command line tool? Are they OK?

    Best regards,
    Leon



  • when i tried to test it in the command prompt in the directory of the sqlite to see if it works it said that "Error: no such table names".



  • How far did you get? What is the output your program generated?



  • It only connects to the database.



  • [quote author="wenks21" date="1305615786"]It only connects to the database.[/quote]
    So... after the "Connected." output, you get nothing else? Your code suggests that you should either get an error or an OK for both the queries you try to execute. If you get an error, please show it.

    Edit:
    I think you are messing up the constructors of your QSqlQuery object. Try to use the constructor that takes a QSqlDatabase argument.



  • yes exactly. after the 'Connected' output nothing else happened.

    how to do the constructor that you are saying? any samples?

    thanks a lot!



  • You might try the QSqlQuery documentation to learn about the different constructors for that class...

    If you get no other output, you might try to set a breakpoint at the place where you last get output, and follow the program execution statement by statement by running in debug mode (F5 in Qt Creator).



  • ok thanks for the info!



  • Hi wenks21,

    Did you resolve your problem?
    I am in the same point... :(



  • You need to open the actual file before opening the database within, like so....
    @
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    QFile newdbfile(QDir::toNativeSeparators(QDir::homePath()+"/test.sqlt"));
    db.setDatabaseName(newdbfile.fileName());

    if (newdbfile.open(QIODevice::ReadWrite))
    {
       if(!db.open())
       {
           qFatal("Failed to connect!");
       }
       else
       qDebug("Connected.");
    }
    

    @

    notice, that I wrapped your db.open() with a newdbfile.open().
    also, this little dance I did sure makes it easy to move around 'tween machines and platforms
    @

    QFile newdbfile&#40;QDir::toNativeSeparators(QDir::homePath(&#41;+"/test.sqlt"));
    db.setDatabaseName(newdbfile.fileName());
    

    @

    I built and ran this code inserted into your code. It works.



  • [quote author="solareclectic" date="1309313429"]You need to open the actual file before opening the database within, like so....[/quote]

    You do not need to open the file. If the code above does not work it is most likely that you

    • have no permission to write to the C:/sqlite3 directory
    • have no directory C:/sqlite3, which prevents the QSQLITE driver from creating the file (this might be the reason why opening - and thus creating - the file solves your problem)


  • Hi.
    I tested your code and it works fine. Did you forget to add QT += sql in your .pro file?



  • Hi,

    I have the same error with solareclectic code, The db is created and after 'Connected' output I don't get nothing, the table is not created.

    Yes, I added QT += sql in my .pro file.

    There is something I omitted because I didn't give importance and it is that I use QSQLITE2 driver instead of QSQLITE, could this be the error?

    Thanks!



  • Qt doc:

    bq. The Qt SQLite 2 plugin is offered for compatibility. Whenever possible, use the version 3 plugin instead.



  • If more than one instance of the application is running the database can be locked. Do not step into this trap as I did several times.



  • Solved.

    Using QSQLITE works perfectly. With QSQLITE2 doesn't.

    Thanks a lot!



  • @wenks21 said:

    qry.prepare("insert into sample1.db (firstname, lastname) values ('John','Dean')");

    check this above line in your code:
    The sql query should be : insert into table_name(column_name,column_name)values (value,value);

    Your are missing out the table_name instead adding your db name. That's wrong.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.