Visual C++ .NET/Database ADO.net/SqlConnection

Материал из .Net Framework эксперт
Версия от 12:06, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

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");
    }
}