1
Answer

connection

Photo of azaam adam

azaam adam

16y
3.9k
1
dear experts im new to c#.net i want to make a connection to connect sql database i want to make in class and i want to call connection in all forms pls help me thaks

Answers (1)

0
Photo of Bechir Bejaoui
NA 20.1k 5.3m 16y




using System;
using System.Data;
using System.Data.SqlClient;

using System.Configuration;
   class CommandExampleSql
   {
      static void Main() 
      {

 

string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["ConnStr"].ToString();


         SqlConnection thisConnection = new SqlConnection(connStr);


         SqlCommand thisCommand = new SqlCommand();
        
         try {
            thisConnection.Open();

            thisCommand.Connection = thisConnection;
 
            thisCommand.CommandText = "...........";// put your query instead of ...
            Console.WriteLine("Ready to execute SQL command: {0}", thisCommand.CommandText);
         }

catch (SqlException ex) {
            Console.WriteLine(ex.Message);
         }

 finally {
            thisConnection.Close();
            Console.WriteLine("Connection Closed.");
         }
      }
   }

Now, in the configuration file add a coneection string as follow

<configuration>

<connectionStrings>

<add name="ConnStr" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\MyData\App_Data\Database.mdf;Integrated Security=True;User Instance=True"/><connectionStrings>

This technique has an advantage is say when your application is already deployed then you can change the connection string from the config file at any time without redefinig the code it's somewhat like the ini file