文章目录

  • 1、问题缘由
  • 2、连接测试
  • 3、寻找连接字符串语句
  • 4、几种可以连接成功的连接字符串
  • 4.1 较早版本
  • 4.2新版本
  • 4.3 官网给出的示例
  • 5、 最简单的连接代码
  • THE END. THANKS FOR WATCHING!


1、问题缘由

SQL server连接到服务器接口 sql server2019连接服务器_sql前两天看视频学习数据库操作时候,使用C++ 连接语句调用 SQL sever 2019怎么也无法调用成功,但本人的错误愿意比较低级,各位高手一般不会犯。但是憋了两天查资料还是查到很多东西,在这里跟大家分享一下。

2、连接测试

SQL server连接到服务器接口 sql server2019连接服务器_sql首先使用VS2017数据库链接工具直接链接SQL server进行测试,如下图所示,点击连接到数据库

SQL server连接到服务器接口 sql server2019连接服务器_sql_03


SQL server连接到服务器接口 sql server2019连接服务器_sql之后选择Microsoft SQL Server作为数据源。

SQL server连接到服务器接口 sql server2019连接服务器_sql_05


SQL server连接到服务器接口 sql server2019连接服务器_sql之后进行服务器名称(即主机名称)的填写,选择身份验证方式为SQL Server身份验证,填写创建数据库时候的用户名和密码,选择要进行连接的数据库名称

SQL server连接到服务器接口 sql server2019连接服务器_ide_07


SQL server连接到服务器接口 sql server2019连接服务器_sql之后点击测试连接,出现下面的界面即连接成功!

SQL server连接到服务器接口 sql server2019连接服务器_ide_09

3、寻找连接字符串语句

SQL server连接到服务器接口 sql server2019连接服务器_sql打开服务器资源管理器

SQL server连接到服务器接口 sql server2019连接服务器_SQL server连接到服务器接口_11


SQL server连接到服务器接口 sql server2019连接服务器_sql打开SQLServer对象资源管理器

SQL server连接到服务器接口 sql server2019连接服务器_sql_13


SQL server连接到服务器接口 sql server2019连接服务器_sqlSQLServer对象资源管理器中打开想要调用的数据库的属性

SQL server连接到服务器接口 sql server2019连接服务器_sql_15


SQL server连接到服务器接口 sql server2019连接服务器_sql在属性中便可以找到连接字符串

SQL server连接到服务器接口 sql server2019连接服务器_SQL server连接到服务器接口_17

4、几种可以连接成功的连接字符串

4.1 较早版本

"Driver=SQL Server;Server=%s;Database=%s;UID=%s;PWD=%s;"

4.2新版本

SQL server连接到服务器接口 sql server2019连接服务器_sql其中server表示服务器名称,Database表示数据库名称,UID表示用户名,PSD表示密码

"Provider='SQLOLEDB'; Data Source=%s ; Initial Catalog=%s;User ID=%s;Password=%s;"

SQL server连接到服务器接口 sql server2019连接服务器_sql其中Data Source表示服务器名称,Initial Catalog表示数据库名称,User ID表示用户名,Password表示密码

4.3 官网给出的示例

SQL server连接到服务器接口 sql server2019连接服务器_sql即上述新版本所述,官网连接如下:
https://docs.microsoft.com/zh-cn/office/client-developer/access/desktop-database-reference/microsoft-ole-db-provider-for-sql-server

5、 最简单的连接代码

SQL server连接到服务器接口 sql server2019连接服务器_sql下面根据SQL server 2019 官方文档示例,给出最简单的连接代码。

_ConnectionPtr pRstAuthors = NULL;
_bstr_t strCnn("Provider='SQLOLEDB'; Data Source='LAPTOP-CRSKGRNV'; Initial Catalog='worker';User ID=sa;Password=123456;");
pRstAuthors.CreateInstance(__uuidof(Connection));
pRstAuthors->Open(strCnn, User ID, Password, adModeUnknown);

SQL server连接到服务器接口 sql server2019连接服务器_sql其中User IDPassword需要根据自己的情况进行修改,连接字符串中是本人的信息,大家也需要根据自己的信息和上述字段解释进行相应的修改,上述完整的代码可以到官网进行copy测试,下面给出官网测试代码和链接:

PS.上述链接代码和下述官网示例本人只在32位系统上跑通了,在64位系统会连接不上,原因本人没有搞清楚,有清楚的大神还烦请指点一下,[抱拳了]。

// BeginSaveCpp.cpp  
// compile with: /EHsc  
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")  
  
#include <ole2.h>  
#include <stdio.h>  
#include <conio.h>  
#include <io.h>  
  
// Function declarations  
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };  
bool FileExists();  
void SaveX1();  
void SaveX2();  
void SaveX3();  
void PrintProviderError(_ConnectionPtr pConnection);  
void PrintComError(_com_error &e);  
  
int main() {  
   if ( FAILED(::CoInitialize(NULL)) )  
      return -1;  
  
   // If File exists in the specified directory, then display error  
   if (!FileExists()) {  
      SaveX1();  
      SaveX2();  
      SaveX3();  
   }  
  
   ::CoUninitialize();  
}  
  
// First, access and save the authors table.  
void SaveX1() {  
   HRESULT hr = S_OK;  
  
   // Define ADO object pointers.  Initialize pointers on define.  
   // These are in the ADODB::  namespace.  
   _RecordsetPtr pRstAuthors = NULL;  
  
   // Definitions of other variables  
   _bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source' ; Initial Catalog='pubs'; Integrated Security='SSPI';");  
  
   try {  
      TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));  
  
      pRstAuthors->Open("SELECT * FROM authors",strCnn, adOpenDynamic,   
         adLockBatchOptimistic, adCmdText);  
  
      // For sake of illustration, save the Recordset to a diskette in XML format.  
      pRstAuthors->Save("c:\\pubs.xml", adPersistXML);  
   }  
   catch(_com_error &e) {  
      // Notify the user of errors, if any.  
      // Pass a connection pointer accessed from the Recordset.  
      _variant_t vtConnect = pRstAuthors->GetActiveConnection();  
  
      // GetActiveConnection returns connect string if connection  
      // is not open, else returns Connection object.  
      switch(vtConnect.vt) {  
      case VT_BSTR:  
         PrintComError(e);  
         break;  
      case VT_DISPATCH:  
         PrintProviderError(vtConnect);  
         break;  
      default:  
         printf("Errors occured.");  
         break;  
      }  
   }  
  
   if (pRstAuthors)  
      if (pRstAuthors->State == adStateOpen)  
         pRstAuthors->Close();  
}  
  
// At this point, you have arrived at your destination.  
// You will access the authors table as a local, disconnected Recordset.   
// Don't forget you must have the MSPersist provider on the machine you   
// are using in order to access the saved file, c:\pubs.xml.  
void SaveX2() {  
   HRESULT hr = S_OK;  
  
   // Define ADO object pointers.  Initialize pointers on define.  
   // These are in the ADODB::  namespace.  
   _RecordsetPtr pRstAuthors = NULL;  
  
   try {  
      TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));  
  
      // For sake of illustration, we specify all parameters.  
      pRstAuthors->Open("c:\\pubs.xml", "Provider='MSPersist';", adOpenForwardOnly, adLockBatchOptimistic, adCmdFile);  
  
      // Now you have a local, disconnected Recordset.  
      // (In this example, changes will not be saved).  
      pRstAuthors->Find("au_lname = 'Carson'", NULL, adSearchForward);  
      if (pRstAuthors->EndOfFile) {  
         printf("Name not found ...\n");  
         pRstAuthors->Close();  
         return;  
      }  
      pRstAuthors->GetFields()->GetItem("City")->PutValue("Chicago");  
      pRstAuthors->Update();  
  
      // Save changes in ADTG format this time, purely for sake of  illustration.   
      // Note that the previous version is still on the diskette as c:\pubs.xml.  
      pRstAuthors->Save("c:\\pubs.adtg", adPersistADTG);  
   }  
   catch(_com_error &e){  
      // Notify the user of errors if any.  
      // Pass a connection pointer accessed from the Recordset.  
      _variant_t vtConnect = pRstAuthors->GetActiveConnection();  
  
      // GetActiveConnection returns connect string if connection  
      // is not open, else returns Connection object.  
      switch(vtConnect.vt) {  
      case VT_BSTR:  
         PrintComError(e);  
         break;  
      case VT_DISPATCH:  
         PrintProviderError(vtConnect);  
         break;  
      default:  
         printf("Errors occured.");  
         break;  
      }  
   }  
  
   if (pRstAuthors)  
      if (pRstAuthors->State == adStateOpen)  
         pRstAuthors->Close();  
}  
  
// Now update the database with changes.  
void SaveX3() {  
   HRESULT hr = S_OK;  
  
   // Define ADO object pointers.  Initialize pointers on define.  
   // These are in the ADODB::  namespace.  
   _RecordsetPtr pRstAuthors = NULL;  
   _ConnectionPtr pCnn = NULL;  
  
   // Definitions of other variables  
   _bstr_t strCnn("Provider='sqloledb'; Data Source='My_Data_Source'; Initial Catalog='pubs'; Integrated Security='SSPI';");  
  
   try {  
      TESTHR(pCnn.CreateInstance(__uuidof(Connection)));  
  
      TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));  
  
      // If there is no ActiveConnection, you can open with defaults.  
      pRstAuthors->Open("c:\\pubs.adtg", "Provider=MSPersist;",  
         adOpenForwardOnly, adLockBatchOptimistic, adCmdFile);  
  
      // Connect to the database, associate the Recordset with the connection,   
      // then update the database table with the changed Recordset.  
      pCnn->Open(strCnn, "", "", NULL);  
  
      pRstAuthors->PutActiveConnection(_variant_t((IDispatch *) pCnn));  
      pRstAuthors->UpdateBatch(adAffectAll);  
   }  
   catch(_com_error &e) {  
      // Notify the user of errors if any.  
      // Pass a connection pointer accessed from the Recordset.  
      _variant_t vtConnect = pRstAuthors->GetActiveConnection();  
  
      // GetActiveConnection returns connect string if connection  
      // is not open, else returns Connection object.  
      switch(vtConnect.vt) {  
      case VT_BSTR:  
         PrintComError(e);  
         break;  
      case VT_DISPATCH:  
         PrintProviderError(vtConnect);  
         break;  
      default:  
         printf("Errors occured.");  
         break;  
      }  
   }  
  
   if (pRstAuthors)  
      if (pRstAuthors->State == adStateOpen)  
         pRstAuthors->Close();  
   if (pCnn)  
      if (pCnn->State == adStateOpen)  
         pCnn->Close();  
}  
  
void PrintProviderError(_ConnectionPtr pConnection) {  
   // Print Provider Errors from Connection object.  
   // pErr is a record object in the Connection's Error collection.  
   ErrorPtr pErr = NULL;  
  
   if ( (pConnection->Errors->Count) > 0) {  
      long nCount = pConnection->Errors->Count;  
  
      // Collection ranges from 0 to nCount -1.  
      for ( long i = 0 ; i < nCount ; i++) {  
         pErr = pConnection->Errors->GetItem(i);  
         printf("Error number: %x\t%s\n", pErr->Number, (LPCSTR) pErr->Description);  
      }  
   }  
}  
  
void PrintComError(_com_error &e) {  
   _bstr_t bstrSource(e.Source());  
   _bstr_t bstrDescription(e.Description());  
  
   // Print COM errors.   
   printf("Error\n");  
   printf("\tCode = %08lx\n", e.Error());  
   printf("\tCode meaning = %s\n", e.ErrorMessage());  
   printf("\tSource = %s\n", (LPCSTR) bstrSource);  
   printf("\tDescription = %s\n", (LPCSTR) bstrDescription);  
}  
  
bool FileExists() {  
   struct _finddata_t xml_file;  
   long hFile;  
  
   if( (hFile = _findfirst("c:\\pubs.xml", &xml_file )) != -1L)  
   {  
      printf( "File already exists!\n" );  
      return(true);  
   }  
   else  
      return (false);  
}

SQL server 2019官网连接示例,链接
https://docs.microsoft.com/en-us/sql/ado/reference/ado-api/save-and-open-methods-example-vc?view=sql-server-ver15

THE END. THANKS FOR WATCHING!