使用SQLAPI++连接到SQL Server



我正试图在远程Ubuntu机器上编写一个c++脚本,该脚本将连接到数据库以检索一些数据。我在另一台远程机器上用Microsoft SQL Server创建了我的数据库。

我已经安装了SQLAPI++,并阅读了SQL server指南和SQL server (ODBC)指南,尝试连接没有任何成功。我认为问题可能是在连接功能,但不知道为什么,我还没有找到任何例子来学习我一直做错了什么。

我第一次看到connect函数是这样使用的:

con.Connect ("test",    // database name
"tester",  // user name
"tester",  // password
SA_SQLServer_Client); //SQL Server Client

但是我需要以某种方式给出存储数据库的机器的IP地址。所以我在(https://www.sqlapi.com/ApiDoc/mssql_odbc/)上找到了以下几行,它允许我在sDBString中传递我的DB的IP。

void Connect(
const SAString &sDBString, 
const SAString &sUserID, 
const SAString &sPassword, 
SAClient_t eSAClient = SA_Client_NotSpecified);

下面是我一直在使用的代码:

#include<stdio.h>
#include<SQLAPI.h>
int main(int argc, char* argv[])
{
// create connection object to connect to database
SAConnection con;
try
{
// connect to database
// in this example, it is Oracle,
// but can also be Sybase, Informix, DB2
// SQLServer, InterBase, SQLBase and ODBC
con.Connect(
const SAString &"[<16.0.0.1>][<SDB>][;<TrustServerCertificate=yes>]",
const SAString &"sa", 
const SAString &"****", 
SAClient_t eSAClient = SA_SQLServer_Client);
printf("We are connected!n");

// Disconnect is optional
// autodisconnect will occur in destructor if needed
con.Disconnect();
printf("We are disconnected!n");
}

catch(SAException & x)
{
// SAConnection::Rollback()
// can also throw an exception
// (if a network error for example),
// we will be ready
try
{
// on error rollback changes
con.Rollback ();
}
catch(SAException &)
{
}
// print error message
printf("%sn", (const char*)x.ErrText());
}
}

当尝试编译时,我得到这些错误:

ConnectToSQLServer.cpp:16:21: error: expected primary-expression before ‘const’
16 |                     const SAString &"[<16.0.0.1>][<SDB>][;<TrustServerCertificate>]",
|                     ^~~~~
ConnectToSQLServer.cpp:17:21: error: expected primary-expression before ‘const’
17 |                     const SAString &"sa",
|                     ^~~~~
ConnectToSQLServer.cpp:18:21: error: expected primary-expression before ‘const’
18 |                     const SAString &"SyAd@CoTe1",
|                     ^~~~~
ConnectToSQLServer.cpp:19:32: error: expected primary-expression before ‘eSAClient’
19 |                     SAClient_t eSAClient = SA_SQLServer_Client);
|                                ^~~~~~~~~

感谢您的宝贵时间。

更新:

错误解决了,现在我得到了一个新的!

undefined reference to `SAConnection::SAConnection()'

这与c++中链接库有关,这看起来非常复杂,我真的不明白它是什么意思。为了使用sqapi .h,我将其包含在其路径(#include "/path/SQLAPI.h")中,就像我在python中导入一样,因为我害怕进入链接库。

如果你能解释一下为什么我做错了,或者如何解决这个问题,我将非常感激。

感谢您的宝贵时间。

你的Connect函数应该是这样的:

con.Connect("[<16.0.0.1>][<SDB>][;<TrustServerCertificate=yes>]","sa", "****", SA_SQLServer_Client);

你的连接字符串应该是这样的:

con.Connect("192.168.50.24SQLINSTANCENAME@MyDatabaseName", "username", "12345", SA_SQLServer_Client);

您可以将IP地址替换为"localhost"或"(localdb)"。"@"字符是必选的,但"TrustServerCertificate"没有必要。

最新更新