A network related error or instance-specific error occured while establishing a connection to sql server when i attach mdf file

StackOverflow https://stackoverflow.com/questions/8335452

Question

iam writing a c# windows application to store some data into a sql server database , but when i make an attempt to attach my mdf database file to visual studio the above error appears here's the code below , what can i do ? Thanks.

public partial class Add_Client : Form
{

    SqlConnection clientConnection;
    string connString;
    SqlCommand insertCommand; 


 public Add_Client()
    {
        InitializeComponent();
        connString = "Data Source=ESLAM\\MSSQLSERVER;Initial Catalog=Clients; Integrated security=true ";
        clientConnection = new SqlConnection();
        clientConnection.ConnectionString = connString;
    }



    private void button1_Click(object sender, EventArgs e)
    {
         try
        {

            SqlCommand insertCommand = new SqlCommand();
            insertCommand.Connection = clientConnection;
            insertCommand.CommandText = "INSERT INTO Client_Info values(@Client_Name,@Autorization_No,@Issue_Type,@Status)";
            insertCommand.Parameters.Add("@Client_Name", SqlDbType.NVarChar, 60).Value = txt_Name.Text;
            insertCommand.Parameters.Add("@Autorization_No", SqlDbType.Int, 60).Value = txt_Auth.Text.ToString();
            insertCommand.Parameters.Add("@Issue_Type", SqlDbType.Text, 200).Value = txt_Iss.Text;
            insertCommand.Parameters.Add("@Status", SqlDbType.Text, 200).Value = txt_Iss.Text;
            //insertCommand.Parameters.Add("@Date To Memorize", SqlDbType.Date, 15).Value=Ca_Mem.se;
            insertCommand.Connection.Open();
            insertCommand.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw ex;

        }
        finally
        {
            if (clientConnection != null)
            {
                clientConnection.Close();
            }

        }
        }
}
Was it helpful?

Solution

Your connection string is just trying to connect to a running instance (.\INSTANCE2) of sql server with the DB (Client) already attached. The error is saying there is no sql server instance running with that name on the local machine. Nothing there will attach anything to anywhere.

Here are instructions on how to get an mdf file attached in sql server express. If you run sqlcmd as a postbuild task in visual studio and run the a modified version of the script for your db and it will start sqlserver and attach your database after you build.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top