Search code examples
sql-server-2008qtqt4

How to connect to SQL Server 2008 with qt?


I am trying to connect to SQL Server 2008 with qt ... I am doing this :

 QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");

 db.setHostName("ITPL_PC1\\SQLEXPRESS");
 db.setDatabaseName("Test");
  db.setUserName("sa");
  db.setPassword("insforia");
  bool ok = db.open();

  //query

  db.close();

I have also added qtsql4 and qtsqld4 libs but now the problem is I am getting an error that database can't be open ... I am very new in qt I don't know how to do this? So any help on how to connect to the database what more should I add or where I am wrong ?


Solution

  • After trying for so much time, I finally managed to get this to work ... here's what I did :

    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC3");
    
    db.setDatabaseName("DRIVER={SQL Server};Server=ITPL_PC1;Database=Test;Uid=sa;Port=1433;Pwd=*******;WSID=.");
    
    db.open();
    
    QSqlQueryModel *model = new QSqlQueryModel;
    
    QString query = "insert into qttable(PID) values('ARINDAM')";
    model->setQuery(query, db);
    
    db.close();