Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    I can't Insert a new data to SQLITE

    General and Desktop
    9
    22
    21151
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • W
      wenks21 last edited by

      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!

      A 1 Reply Last reply Reply Quote 0
      • L
        leon.anavi last edited by

        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

        http://anavi.org/

        1 Reply Last reply Reply Quote 0
        • A
          andre last edited by

          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.

          1 Reply Last reply Reply Quote 0
          • L
            leon.anavi last edited by

            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.

            http://anavi.org/

            1 Reply Last reply Reply Quote 0
            • W
              wenks21 last edited by

              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?

              1 Reply Last reply Reply Quote 0
              • L
                leon.anavi last edited by

                [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

                http://anavi.org/

                1 Reply Last reply Reply Quote 0
                • W
                  wenks21 last edited by

                  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".

                  1 Reply Last reply Reply Quote 0
                  • A
                    andre last edited by

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

                    1 Reply Last reply Reply Quote 0
                    • W
                      wenks21 last edited by

                      It only connects to the database.

                      1 Reply Last reply Reply Quote 0
                      • A
                        andre last edited by

                        [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.

                        1 Reply Last reply Reply Quote 0
                        • W
                          wenks21 last edited by

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

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

                          thanks a lot!

                          1 Reply Last reply Reply Quote 0
                          • A
                            andre last edited by

                            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).

                            1 Reply Last reply Reply Quote 0
                            • W
                              wenks21 last edited by

                              ok thanks for the info!

                              1 Reply Last reply Reply Quote 0
                              • A
                                aureliocano last edited by

                                Hi wenks21,

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

                                1 Reply Last reply Reply Quote 0
                                • S
                                  solareclectic last edited by

                                  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.

                                  1 Reply Last reply Reply Quote 0
                                  • L
                                    lgeyer last edited by

                                    [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)
                                    1 Reply Last reply Reply Quote 0
                                    • S
                                      silver47 last edited by

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

                                      sorry for my english :(

                                      1 Reply Last reply Reply Quote 0
                                      • A
                                        aureliocano last edited by

                                        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!

                                        1 Reply Last reply Reply Quote 0
                                        • S
                                          silver47 last edited by

                                          Qt doc:

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

                                          sorry for my english :(

                                          1 Reply Last reply Reply Quote 0
                                          • D
                                            dialingo last edited by

                                            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.

                                            1 Reply Last reply Reply Quote 0
                                            • First post
                                              Last post