Showing posts with label Attach database from drive of sql. Show all posts
Showing posts with label Attach database from drive of sql. Show all posts

Friday, 22 April 2016

How to create connection class in c# , how to attach database from mdf file, How to attach database from Pendrive

Create connection class in c#(In App-Code Folder) 

How to attach database from mdf file 

How to attach database from Pendrive


First of all open your web.config file of your application
and write this following code

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
   
   <!-- This code use when your database have password -- >
  <add name="CS"  connectionString="Data Source=VINEET-PC\SQLEXPRESS;Initial        Catalog=yourdbname;User ID=dbid;Password=dbpassword;Integrated Security=True;" providerName="System.Data.SqlClient"/>

<!-- This code use when your database with no password -- >
    <add name="CS" connectionString="Data Source=VINEET-PC\SQLEXPRESS;Initial Catalog=yourdbname;Integrated Security=True" providerName="System.Data.SqlClient"/>

<!-- This code use when your database access from other drive Suppose G is your drive -- >
     <add name="CS"  connectionString="Data Source=.\SQLExpress;AttachDbFilename=G:\youdabase.mdf;Integrated Security=True;User Instance=True;"providerName="System.Data.SqlClient" />


  </connectionStrings>
  <system.web>
    <customErrors mode="Off"/>
    <compilation debug="true" targetFramework="4.0"/>
    
  </system.web>
 
</configuration>

Now Create A class File in app_code folder using following code with name of Connection.cs

using System;
using System.Collections.Generic;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Configuration;
using System.Data;

/// <summary>
/// Summary description for Connection
/// </summary>
public class Connection
{
    public static SqlConnection con = new 
SqlConnection(ConfigurationManager.ConnectionStrings["CS"].ConnectionString) ; 
}



Now this connection file has been created
You can use your connection in any cs file like this

Connection.con.Open();
Connection.con.Close();
Connection.con

these above code is for attache database from other drive  for your application, so you use 3rd connectionstring for connection.