我們在遠程Windows服務器上有一個Microsoft Sql 2014數據庫。我正在嘗試開發一個連接到這個數據庫的QT GUI應用程序。該應用程序在Linux/C++環境中。我嘗試使用QtSql API連接到該數據庫。如何從linux C++應用程序訪問SQL服務器?
bool MainWindow::connect()
{
QSqlDatabase db=QSqlDatabase::addDatabase("QODBC");//I am not sure if I am calling this correctly
db.setHostName("III");
db.setDatabaseName("YYY");
db.setUserName("YYY");
db.setPassword("XX");
bool ok = db.open();
if(ok==true)
{
QSqlQuery query;
query.exec("SELECT * FROM Subjects");
while (query.next())
{
int phy = query.value(0).toInt();
int chem = query.value(1).toInt();
ui->lineEdit_2->setText(QString::number(phy));
ui->lineEdit_3->setText(QString::number(chem));
}
}
else
{
qDebug()<<db.lastError();
}
return ok;
}
它給我的錯誤是:
QSqlDatabase: QODBC driver not loaded
QSqlDatabase: available drivers: QSQLITE QMYSQL QMYSQL3 QPSQL QPSQL7
QSqlError("", "Driver not loaded", "Driver not loaded")
我試圖出口到我的Qt project.Still SQL驅動的路徑它沒有work.Then我讀過一些文章,我發現我需要mssql-tools以及我的Linux機器上的ODBC Driver。我試圖根據這個網站上安裝此:
https://blogs.msdn.microsoft.com/sqlnativeclient/2016/10/20/odbc-driver-13-0-for-linux-released/
,發現這不僅會在15.10 & 16.04在我的Linux機器(14.04 Ubuntu的),但工作。
The following packages have unmet dependencies:
mssql-tools :
Depends: libc6 (>= 2.21) but 2.19-0ubuntu6.9 is to be installed
Depends: libstdc++6 (>= 5.2) but 4.8.4-2ubuntu1~14.04.3 is to be installed
Depends: msodbcsql (>= 13.1.0.0) but it is not going to be installed
Depends: msodbcsql (< 13.2.0.0) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
然後我用碼頭工人從這裏: https://hub.docker.com/r/taylorbarrick/mssql-server-linux-tools/
我能安裝成功,但是當我運行
$docker run -t taylorbarrick/mssql-server-linux-tools sqlcmd -d <dbname> -H <host> -U <username> -P <password>
我再次收到錯誤。
Sqlcmd: Error: Microsoft ODBC Driver 13 for SQL Server : Login timeout expired.
Sqlcmd: Error: Microsoft ODBC Driver 13 for SQL Server : TCP Provider: Error code 0x2749.
Sqlcmd: Error: Microsoft ODBC Driver 13 for SQL Server : A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online..
但是,當使用可視化界面我可以連接到sql數據庫。請幫助。
還要確保QODBC驅動程序('.so'文件)存儲在'$ QTDIR/5.6/gcc_64/plugins/sqldrivers /'和'unixodbc-dev'軟件包中的某處必須安裝以構建驅動程序! –
非常感謝您提供解決方案並解釋得非常好。但是,我使用外部數據包裝器(Foreign Data Wrapper)概念解決了這個問題,因此使我的postgres數據庫能夠訪問SQL數據庫的「視圖」。我不必在postgres客戶端安裝任何東西,但只能在服務器端安裝。正因爲如此,我的QT應用程序現在不需要改變。對於我的應用程序,它定期調用postgress db.This運作完美。但我接受你的答案。 – Minion