简体   繁体   English

通过QT C ++连接到SQL Server 2005

[英]Connecting to SQL server 2005 through QT C++

I have a server of windows server 2003 and its IP on my local network is 192.168.1.220 This server has SOL server 2005 express edition installed. 我有一台Windows Server 2003服务器,其本地网络上的IP为192.168.1.220。该服务器已安装SOL Server 2005 Express Edition。 This SQL server has a database called amir. 该SQL Server具有一个名为amir的数据库。

I want to connect to it from a Linux client on the same network. 我想从同一网络上的Linux客户端连接到它。 SQL server service using port 1617 on my server and I used this port to connect to the server using java. SQL Server服务使用服务器上的端口1617,我使用此端口使用Java连接到服务器。

Wow i want to use QT C++ but my code doesn't work. 哇,我想使用QT C ++,但是我的代码不起作用。

This is my code: 这是我的代码:

#include <QtCore/QCoreApplication>
#include <iostream>
#include <QSqldatabase>
#include <QSqldriver>
int main(int argc, char *argv[])
{
   QCoreApplication a(argc, argv);
   QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
   bool test=db.isValid();//true
   test=db.isDriverAvailable("QODBC");//true
   db.setHostName("192.168.1.220\\SQLEXPRESS");
   db.setDatabaseName("DRIVER={SQL Server};SERVER=192.168.1.220\\SQLEXPRESS:1617;DATABASE=amir");
   db.setUserName("sa");
   db.setPassword("amir");
   db.setPort(1617);
   test=db.isValid();//true
   if(!db.open())
   {
      cout<<endl<<"not connected"<<endl;
      QString error=db.lastError().text();
      cout<<error.toLocal8Bit().data();
      return false;
   }
   else
      cout<<endl<<"connected"<<endl;
      return true;
 }

Every time i try this it out "not connected" and the error is 每次我尝试这个“未连接”,错误是

[unixODBC][Driver Manager]Data source name not found, and no default driver specified QODBC3: Unable to connect [unixODBC] [驱动程序管理器]找不到数据源名称,并且未指定默认驱动程序QODBC3:无法连接

Using these parameters I can connect using java 使用这些参数,我可以使用Java连接

So what is the wrong here? 那么,这是怎么了? and if there is another fasting way to connect to the SQL server using qt c++ than ODBC driver. 以及是否存在使用qt c ++而非ODBC驱动程序连接到SQL Server的另一种禁食方式。

You need to setup a data source name on your server to connect through ODBC. 您需要在服务器上设置数据源名称以通过ODBC连接。 Here is some code that I use to setup a DSN: 这是我用来设置DSN的一些代码:

QString SQLServerProvider::buildDSN(QString server, QString database, QString username, QString password)
{
#ifdef Q_WS_MACX
    QString dsn = QString("DRIVER=/usr/local/lib/libtdsodbc.so;SERVER=%1;TDS_VERSION=8pClient;DATABASE=%2;PORT=1433;UID=%3;PWD=%4;").arg(server).arg(database).arg(username).arg(password);
#endif

#ifdef Q_WS_X11
    QString dsn = QString("DRIVER={FreeTDS};SERVER=%1;TDS_VERSION=8.0;PORT=1433;DATABASE=%2;UID=%3;PWD=%4;").arg(server).arg(database).arg(username).arg(password);
#endif

#ifdef Q_WS_WIN
    QString dsn = QString("DRIVER={SQL SERVER};SERVER=%1;DATABASE=%2;UID=%3;PWD=%4;").arg(server).arg(database).arg(username).arg(password);
#endif
    return dsn;
}
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC", databaseName);
db.setDatabaseName(buildDSN(server, database, username, password));

Here is some code that I forgot to put in the initial post: 这是我忘了写在初始帖子中的一些代码:

    #ifdef Q_WS_X11
    QString dir = QDir::homePath();
    QDir d;
    QString libdir = d.absolutePath();

    QFile odbcinst(dir + "/.odbcinst.ini");
    if(!odbcinst.exists())
    {
        odbcinst.open(QIODevice::WriteOnly | QIODevice::Text);
        QTextStream out(&odbcinst);
        out << "[FreeTDS]\n";
        out << "Description = v0.91 with protocol v8.0\n";
        out << "Driver = " + libdir + "/libtdsodbc.so\n";
        out << "Setup = " + libdir + "/libtdsodbc.so\n";
        out << "FileUsage = 1";
        odbcinst.close();
    }
    else
    {
        QList<QString> lines;

        odbcinst.open(QIODevice::ReadOnly | QIODevice::Text);
        QTextStream readfile(&odbcinst);

        int i = 0, lnbr = 0;
        bool found = false;
        while(!readfile.atEnd())
        {
            QString line = readfile.readLine();
            if(line.contains("[FreeTDS]"))
            {
                lnbr = i;
                found = true;
            }
            lines.append(line);
            i++;
        }
        odbcinst.close();

        // append to end
        if(!found)
        {
            // append to the end
            odbcinst.open(QIODevice::Append | QIODevice::Text);
            QTextStream file(&odbcinst);

            file << "\n[FreeTDS]\n";
            file << "Description = v0.91 with protocol v8.0\n";
            file << "Driver = " + libdir + "/libtdsodbc.so\n";
            file << "Setup = " + libdir + "/libtdsodbc.so\n";
            file << "FileUsage = 1";
            odbcinst.close();
        }
        else // update existing entry
        {
            qDebug() << "Found an entry for FreeTDS. Updating driver to " + libdir + "/libtdsodbc.so.";
            qDebug() << lines[lnbr+2];
            qDebug() << lines[lnbr+3];

            lines.replace(lnbr + 2, "Driver = " + libdir + "/libtdsodbc.so");
            lines.replace(lnbr + 3, "Setup = " + libdir + "/libtdsodbc.so");

            QString text;
            for(int j = 0; j < lines.count(); j++)
            {
                text.append(lines[j] + "\n");
            }

            odbcinst.open(QIODevice::WriteOnly | QIODevice::Text);
            QTextStream updatefile(&odbcinst);
            updatefile << text;
            odbcinst.close();
        }

    }
#endif

This code creates the .odbcinst.ini file in your home directory if it doesn't exist and adds an entry for FreeTDS. 如果不存在,此代码将在您的主目录中创建.odbcinst.ini文件,并为FreeTDS添加一个条目。 If it does exist, it will append to the end of the file. 如果存在,它将附加到文件末尾。 If an entry for FreeTDS exists in the file already, it will update the existing file. 如果文件中已经存在FreeTDS条目,它将更新现有文件。 Here's a guide for setting up FreeTDS if you haven't already: http://pzuk.wordpress.com/2012/02/03/how-to-make-freetds-unixodbc-and-qt-working-together/ 如果您尚未设置FreeTDS,请参见以下指南: http : //pzuk.wordpress.com/2012/02/03/how-to-make-freetds-unixodbc-and-qt-working-together/

Note, that the code for configuring FreeTDS that I posted is only required if you want to bundle FreeTDS with your application and have the libary path setup correctly from where you launch. 请注意,仅当您要将FreeTDS与应用程序捆绑在一起并从启动位置正确设置了库路径时,才需要我发布的用于配置FreeTDS的代码。 It runs as a standard user and not as root so everything is done in the local user account. 它以标准用户身份而不是root用户身份运行,因此一切都在本地用户帐户中完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM