What is passing parameters to SQL and why do I need it?

后端 未结 5 880
小蘑菇
小蘑菇 2020-11-27 20:31

Beginner here:

In this answer to my question of how to insert data into SQL Server he mentioned passing parameters instead of string concatenation like I currently

5条回答
  •  余生分开走
    2020-11-27 21:11

    Here is an example:

            SqlConnection myConn = new SqlConnection("my connection string");
    
            SqlCommand myCmd = new SqlCommand("myStoredProcName", myConn);
    
            myCmd.CommandType = CommandType.StoredProcedure;
    
            myCmd.Parameters.AddWithValue("@cGroupID", 0).Direction = ParameterDirection.InputOutput;
            myCmd.Parameters.AddWithValue("@gType", "C");
            myCmd.Parameters.AddWithValue("@requirement", "Y");
            myCmd.Parameters.AddWithValue("@usercode", "XX");
    
            myConn.Open();
            myCmd.ExecuteNonQuery();
    
            int covID = (int)myCmd.Parameters["@cGroupID"].Value;
    

    Using Parameters is a good way to prevent some errors, and help stop injection vectors. It also allows OUTPUT parameters, as in the example above where cGroupID comes back with a value that I can access.

提交回复
热议问题