Skip to content
Advertisement

Inserting data row into a sql table from another sql table in C#

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?

Advertisement

Answer

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();
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement