2

Context: I'm developing an app for windows in Visual Studio that has a table of stock materials and another of buyed materials, both in a Sql Server. I want that every time you buy something it is added into the stock table.

I'm new in using SQL with c# combined.

I'm trying this from a tutorial, but does nothing. Not even an exception.

            string cmdString = "Insert INTO Table1 (Column_name) VALUES (@val1)";
            string connString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True";
            using (SqlConnection conn = new SqlConnection(connString))
            {
                using (SqlCommand comm = conn.CreateCommand())
                {

                    comm.Connection = conn;
                    comm.CommandText = cmdString;                    
                    comm.Parameters.AddWithValue("@val1", Value);
                    try
                    {
                        conn.Open();
                        comm.ExecuteNonQuery();
                        conn.Close()
                    }
                    catch(SqlException ex)
                    {
                        
                    }
                }
            }

Is this totally wrong or should i change something?

Edit: I figured out. I was inserting val1 in a column, but the ID was empty so it throws an NullId exception. For some reason in debug mode I wasn't able to see it.

Thanks for the help. If I have the Table1 with autoincrement why it needs an ID? There is a way that when something is inserted the Id generates automatically?

11
  • Have you inserted anything into the database? Commented Oct 5, 2020 at 10:39
  • You should probably do something in the catch block. Or did you mean you never end up in the catch block? Commented Oct 5, 2020 at 10:45
  • "AddWithValue is Evil" Commented Oct 5, 2020 at 10:47
  • You'd be better off having a trigger execute on data insert and do the insert into the other table. Commented Oct 5, 2020 at 10:48
  • 3
    Does this answer your question? Why saving changes to a database fails? Commented Oct 5, 2020 at 11:33

1 Answer 1

1

You can use this query to insert data like that :

{
    if (con.State == ConnectionState.Open)
        con.Close();
}   
{
    SqlCommand cmd0561 = new SqlCommand(@"insert into Table1 (value1,value1) values  
    (@value1,@timee)", con);
    cmd0561.Parameters.AddWithValue("@value1", value1.Text.Trim);
    cmd0561.Parameters.AddWithValue("@value2", value2.Text.Trim);
    con.Open();
    cmd0561.ExecuteNonQuery();
    con.Close();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.