0

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>
Md Farid Uddin Kiron
  • 16,817
  • 3
  • 17
  • 43
  • What error you are getting on debugging and you should take care of your query to prevent the SQL injection. – Suraj Kumar Feb 25 '20 at 12:42
  • 6
    _"I'm not even getting any exception..."_ So what **exactly** happens? Did you [debug](https://stackoverflow.com/q/25385173/5528593)? And btw: your code is open to **[SQL injection](http://www.bobby-tables.com)** please use parameterized queries. – René Vogt Feb 25 '20 at 12:43
  • Hi @coder1234. I would suggest reading about IDiposable, an interface to communicate that the instance created should be disposed to correctly release unmanaged resources. Example `using(var connection = new SqlConnection()) { /* Code goes here */ }`. After the scope the connection will be correctly disposed. Secondly the SqlCommand should have its parameter parameterized to mitigate sql injection attacks. `var command = new SqlCommand("insert into SomeTable values (@myValue); command.ParametersWithValue)(@myValue, "Actual value")` – joacar Feb 25 '20 at 12:45
  • 1
    [Can we stop using AddWithValue() already](https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/), @joacar ? – Thom A Feb 25 '20 at 12:46
  • i have tried with parameterized as well.it's not working with that too – coder1234 Feb 25 '20 at 12:48
  • @coder1234, use parameterized queries with proper types. That may not address your immediate problem though, since you haven't included details in your question. Perhaps the problem is the actual value for `textBox1.Text` is `';DROP TABLE Client_Name;--` – Dan Guzman Feb 25 '20 at 12:56
  • ExecuteNonQuery error CS0103: The name 'ExecuteNonQuery' does not exist in the current context..i am gettting this error on debugging but i am able to fetch data facing problem in inserting data – coder1234 Feb 25 '20 at 12:57
  • @coder1234: I don't see how this code could be producing that error. That's also a *compile time* error, so if the code doesn't even compile then that would certainly explain why it's not inserting any data into the database, so it's not really clear what the expectation is here. Can you double-check that this is the *exact* code which produces the error, and include the *exact* information of the error? In cases like this it's even acceptable to include a screenshot of the error as it's observed. (But also include the error message as text of course.) – David Feb 25 '20 at 13:04
  • 1
    You need to include these two lines to your code behind i.e., using System.Data.SqlClient; using System.Data; – Suraj Kumar Feb 25 '20 at 13:06
  • @coder1234 I have given you complete example which would resolved your issue. let me know your update – Md Farid Uddin Kiron Feb 25 '20 at 15:39

1 Answers1

0

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.

Md Farid Uddin Kiron
  • 16,817
  • 3
  • 17
  • 43