Monday, May 4, 2009

SQL Data Base Connection in C#

1. Connection with Your Database in Your Code, Data source is IP of data server:-

SqlConnection conn;

conn = new SqlConnection("Data Source=192.168.100.44;

Initial Catalog=DataBaseName;

Persist Security Info=True;

User ID=scoat;

Password=tiger");

conn.Open();

1.1 Connection Using WebConfig, Add this in webconfig:-

<connectionStrings>

<add name="SampleConnectionString"

connectionString="data source=192.168.100.44;

Initial Catalog=DataBaseName;

Persist Security Info=True;

User ID=scoat;

Password=tiger" providerName="System.Data.SqlClient"/>

<connectionStrings>

1.2 Add This In your code:-

SqlConnection conn = New SqlConnection

(ConfigurationManager

.ConnectionStrings["SampleConnectionString"].ConnectionString);

2.Spiecify store procedure Want To Use:-

SqlCommand cmd = new SqlCommand("ProcedureName", conn);

cmd.CommandType = CommandType.StoredProcedure;

3.Pass Parameter To Store Procedure:-

SqlParameter parameterObj = cmd.Parameters.Add("@ProcedureVariable",SqlDbType.Int);

parameterObj.Value = DataToPass;

4. Execut Procedure And Close Connection:-

SqlDataReader thisReader = cmd.ExecuteReader();

thisReader.Close();

conn.Close();

No comments: