Parameterize SQL query

前端 未结 5 648
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 03:07

    Firstly you are not executing the command, you'll need to call comm.ExecuteNonQuery();, secondly your SQL string will be wrong. This line:

    var sqlstring = string.Format("INSERT INTO Contacts ([First] ,[Last] ,[Address] ,[City],
    [State],[ZIP]) VALUES {0}, {1}, {2}, {3}, {4}, {5})", @first, @last, @addy, @city1, 
    @stat, @zippy)
    

    Can just be:

    var sqlstring = "INSERT INTO Contacts ([First] ,[Last] ,[Address] ,[City] ,[State],[ZIP]) 
                     VALUES (@first, @last, @addy, @city1, @stat, @zippy)";
    

    Thridly you are not actually adding your parameters to your command. You create a parameter like so:

    SqlParameter zipparam;
    zipparam = new SqlParameter();
    zipparam.ParameterName = "@zippy";
    zipparam.Value = zippy;
    

    But you are adding this:

    comm.Parameters.Add("@zippy", SqlDbType.SmallInt);
    

    with no reference to zipparam. This means that the value zippy is never actually added to the command. You could do this all in one line using:

    comm.Parameters.Add(new SqlParameter(@Zippy, SqlDbType.SmallInt)).Value = zippy;
    

提交回复
热议问题