9

I have got a local SQL Server DB, up and running, and I am trying to connect to it in a seemingly failproof way:

new SqlConnection(@"Server=(localdb)\v12.0;Integrated Security=true;Database=MyDBName;");

However, this line throws an exception: "'ServerVersion' threw an exception of type 'System.InvalidOperationException'"? What could I do to fix it?

I have run

sqllocaldb create "v12.0"

but it seems to make no difference.

enter image description here

enter image description here

Yulia V
  • 3,507
  • 10
  • 31
  • 64

2 Answers2

1

Step 1: go to WebConfig File and Write this Code:

enter code here

 <connectionStrings>

 <add name ="MyDbConn" ---> write same it is 

     connectionString="Server=SYED\SQLEXPRESS; database=Templete_2_DB; 
     Trusted_Connection=True" providerName="System.data.sqlclient"
     />
  </connectionStrings>

code here

SYED\SQLEXPRESS; ---> this is your servername Templete_2_DB; ----> this is your database name

step 2: Go to your page event and write code like this..

enter code here


 SqlConnection con = new SqlConnection(

 WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString);

 SqlCommand cmd = new SqlCommand("select * from Accounts_Data where 
 UserName=@username and Password=@password", con);
        cmd.Parameters.AddWithValue("@username", txt_username.Text);
        cmd.Parameters.AddWithValue("@password", txt_userPassword.Text);
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        sda.Fill(dt);
        con.Open();
        int i = cmd.ExecuteNonQuery();
        con.Close();

        if (dt.Rows.Count > 0)
        {
            Response.Redirect("Default.aspx");
        }

code here

Go ahead... in this you will be guided

https://www.youtube.com/watch?v=Mo0ECWKVVDU

-1

Create a method:

private void connection()
{
    con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStrSheebu"].ConnectionString);
}

set in web.config as:

<connectionStrings>
    <add name="conStrSheebu" connectionString="Data Source=(local);Initial Catalog=Sheebu;User ID=sa;Password = AnsarI" providerName="System.Data.SqlClient" />
</connectionStrings>
Machavity
  • 30,841
  • 27
  • 92
  • 100