我正在尝试通过网络连接到远程计算机上的SQL Server实例。我有一个IP地址,一个端口,数据库名称,一个用户名和一个密码。我正在尝试使用Microsoft股票的SQL函数(即SQLConnect
,SQLPrepare
,SQLExecute
等)
我的代码如下:
{
SQLHENV henv;
SQLHDBC hdbc;
SQLHSTMT hstmt;
SQLRETURN retcode;
SQLCHAR * error = new SQLCHAR[5];
SQLCHAR * OutConnStr = (SQLCHAR *)malloc(255);
SQLSMALLINT * OutConnStrLen = (SQLSMALLINT *)malloc(255);
// Allocate environment handle
retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
// Set the ODBC version environment attribute
if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
{
retcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);
// Allocate connection handle
if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
{
retcode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
// Set login timeout to 5 seconds
if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
{
SQLSetConnectAttr(hdbc, SQL_LOGIN_TIMEOUT, (SQLPOINTER)5, 0);
// Connect to data source
retcode = SQLDriverConnect(hdbc, nullptr, (SQLCHAR*)"Provider=SQLOLEDB.1;Persist Security Info=False;User ID=myid;Initial Catalog=mydb;Data Source=<server ip address>,1433", 127,
NULL, NULL, NULL, NULL);
SQLGetDiagRec(SQL_HANDLE_DBC, hdbc, 1, error, NULL, NULL, NULL, NULL);
SQLAllocStmt(hdbc, &hstmt);
SQLPrepare(hstmt, (SQLCHAR *)"INSERT INTO mytable VALUES(***********); ", SQL_NTS);
SQLExecute(hstmt);
// Allocate statement handle
if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) {
retcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
// Process data
if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) {
SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
}
SQLDisconnect(hdbc);
}
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
}
}
SQLFreeHandle(SQL_HANDLE_ENV, henv);
}
return;
}
但是,当我运行此代码时,我得到了IM002
在参数ServerName中指定的数据源名称不是 在系统信息中找到,也没有默认驱动程序 规格
我尝试使用SQLDriverConnect
,且连接字符串不为connectionstrings.com,但出现相同的错误。