简体   繁体   中英

Unable to insert values in sql server local db using c#

I'm unable to insert data into table. we are using local db. I'm not even getting any exception

string constr = ConfigurationManager.ConnectionStrings["server"].ConnectionString;
private void button1_Click(object sender, EventArgs e)
{
  try
  {
    SqlConnection con = new SqlConnection(constr);
    SqlCommand cmd = new SqlCommand("insert into Client_Name(Name) values('" + textBox1.Text + "')",con);
    cmd.Connection = con;
    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();

   }
   catch (Exception ee)
   {
     Console.Write("Exception");
   }
}

In app.config

<connectionStrings>
<add name="server" connectionString="Data Source =          (LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\msm.mdf;Integrated 
Security=True;Connect Timeout=30"                  providerName="System.Data.SqlClient" />
</connectionStrings>

I have tried all the possible way, and got the best solution considering your scenario.

During an hour observation got to know due database connection persistence issue you were having that problem try below snippet would work as expected.

            string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\msm.mdf;Connect Timeout=30;Integrated Security=True;";

            using (var _connection = new SqlConnection(connectionString))
            {
                _connection.Open();

                using (SqlCommand command = new SqlCommand("Insert into [LocalTestTable] values (@name,@description)", _connection))
                {
                    command.Parameters.AddWithValue("@name", "TestFlatName");
                    command.Parameters.AddWithValue("@description", "TestFlatDescription");
                    SqlDataReader sqlDataReader = command.ExecuteReader();
                    sqlDataReader.Close();
                }
                _connection.Close();

            }

Hope that will resolve your problem without having anymore issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM