Visual C++ .NET/Database ADO.net/SqlConnection — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
м (1 версия)
 
(нет различий)

Текущая версия на 12:06, 26 мая 2010

Close database connection in destructor

 
#include "stdafx.h"
#using "System.dll"
#using "System.Data.dll"
using namespace System;
using namespace System::Data::SqlClient;
ref class DataConnection
{
   SqlConnection^ conn;
   public:
   DataConnection()
   {
      conn = gcnew SqlConnection("Server=(local);Uid=sa;Pwd=****;Initial Catalog=master");
      conn->Open();
   }

   ~DataConnection()
   {
      this->!DataConnection();
   }
   !DataConnection()
   {
      try {
        Console::WriteLine("Closing connection...");
        conn->Close();
      }
      catch(Exception^ e)
      {
         Console::WriteLine("Error occurred! " + e->Message);
      }
   }
};
int main()
{
   DataConnection connection1;
   DataConnection^ connection2 = gcnew DataConnection();
   GC::Collect();
}


Make connection to database with SqlConnection

 
#include "stdafx.h"

using namespace System;
using namespace System::Data;
using namespace System::Data::SqlClient;
using namespace System::Configuration;
void main()
{
    SqlConnection^ connection = gcnew SqlConnection();
  connection->ConnectionString = "SQLConnection";
  try
    {
        connection->Open();
        Console::WriteLine("We got a connection!");
    }
    catch (SqlException ^e)
    {
        Console::WriteLine("No connection the following error occurred: {0}",
            e->Message);
    }
    finally
    {
        connection->Close();
        Console::WriteLine("The connection to the database has been closed");
    }
}