connection
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
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Bechir BejaouiPosted Dec 6, 2008, 5:01 AM
using System;using System.Data;
using System.Data.SqlClient;
using System.Configuration;class CommandExampleSql
{
static void Main()
{
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);
}
Now, in the configuration file add a coneection string as followfinally {
thisConnection.Close();
Console.WriteLine("Connection Closed.");
}
}
}
<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