Parameterize SQL query

前端 未结 5 649
Happy的楠姐
Happy的楠姐 2020-12-04 02:35

Many posts about Parameters in SQL with C# but I am still missing something. I am not getting an error message but no data is inserted. What is missing? I have text boxes na

5条回答
  •  攒了一身酷
    2020-12-04 02:53

    You forgot to execute the command ;)

    EDIT: you also didn't use the parameters that you created at the beginning of the method.

        ...
        try
        {
            conn.Open();
            //SqlTransaction trans = conn.BeginTransaction();
            //comm.Transaction = trans;
            comm.Parameters.Add(firstparam);
            comm.Parameters.Add(lastparam);
            comm.Parameters.Add(addressparam);
            comm.Parameters.Add(cityparam);
            comm.Parameters.Add(stateparam);
            comm.Parameters.Add(zipparam);
    
            // This is what you forgot:
            comm.ExecuteNonQuery();
        }
        ...
    

    BTW, don't do things like that:

        catch (Exception ex1)
        {
            throw new Exception(ex1.ToString(), ex1);
        }
    

    It's useless, it just adds a new level of exception without adding anything useful. Just let the exception bubble up the stack until it reaches a catch block that actually does something useful.

提交回复
热议问题