QSqlDatabase how to connect to a database



  • hello,

    how can you connect to a database?
    i have the db.sql file and this folowing code:
    @
    QSqlDatabase m_db = QSqlDatabase::addDatabase("QSQLITE");
    m_db.setHostName("localhost");
    m_db.setDatabaseName("db.sql");
    m_db.setUserName("user");
    m_db.setPassword("");
    bool ok = m_db.open();
    @
    please help


  • Lifetime Qt Champion

    Hi,

    What is the problem ? Getting an error ?



  • basicly getting nothing....
    @
    if(ok)
    {
    QSqlQuery query;
    if(query.exec("SELECT Name FROM City"))
    while(query.next())
    qDebug()<<query.value("City");
    qDebug()<<"database open";
    }
    @

    although it does print database open.
    i think it does not connect to my database, but it connects to something.



  • if someone has a really basic sql database and the code that connects to it, please post the link.



  • Hi, what happens, if you use:
    @
    qDebug << query.value("City").toString();
    @


  • Lifetime Qt Champion

    Also, check what error you get if the query fails



  • [quote author="mititelud" date="1394549278"]hello,

    how can you connect to a database?
    i have the db.sql file and this folowing code:
    @
    QSqlDatabase m_db = QSqlDatabase::addDatabase("QSQLITE");
    m_db.setHostName("localhost");
    m_db.setDatabaseName("db.sql");
    m_db.setUserName("user");
    m_db.setPassword("");
    bool ok = m_db.open();
    @
    please help[/quote]

    SQLite is a Zero-Configured DB.
    There is no need to give HostName, UserName,Password.
    Here you are given databasename as db.sql which is not an sqlilte DB
    sqlite DB extension is .sqlite.

    Here is the sample code---

    MyDB=QSqlDatabase::addDatabase("QSQLITE");
    MyDB.setDatabaseName("D:/department.sqlite");
    QFileInfo checkfile&#40;"D:/department.sqlite"&#41;;
    if(checkfile.isFile&#40;&#41;)
    {
        if(MyDB.open())
        {
           qDebug()  << "connected..";
        }
    
    }
    

    else
    {
    qDebug() << "Not Connected..";
    }

    hope it helps


  • Lifetime Qt Champion

    The file extension doesn't need to be sqlite. It's the file content that is important.

    Also, since you are using a relative file path you need to ensure that the database file is in the same folder as the application. Otherwise just give the absolute path to it.


Log in to reply
 

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