none
Question to SqlCommand RRS feed

  • Question

  • Hi,
    How to add parameter to SqlCommand below?

    using (SqlCommand sqlCmd = new SqlCommand("SELECT ...", sqlConn)) 
                    {
                        sqlConn.Open();
                        sqlCmd.CommandType = CommandType.Text;
                        SqlDataAdapter sqlAd = new SqlDataAdapter(sqlCmd);
                        DataTable sqlDt = new DataTable();
                        sqlAd.Fill(sqlDt);
                        ...
    


    Many Thanks & Best Regards, Hua Min

    Monday, February 12, 2018 7:55 AM

All replies

  • You can find example here.

    Just provide parameter placeholder to sqlCmd CommandText, and then add the parameters to sqlCmd, and it's done.

    Monday, February 12, 2018 10:04 AM
    Answerer
  •             using (SqlCommand sqlCmd = new SqlCommand("SELECT A from B Where Y=Z", sqlConn))
                {
                    sqlConn.Open();
                    sqlCmd.CommandType = CommandType.Text;
                    sqlCmd.Parameters.AddWithValue("Z","Chen");
                    SqlDataAdapter sqlAd = new SqlDataAdapter(sqlCmd);
                    DataTable sqlDt = new DataTable();
                    sqlAd.Fill(sqlDt);

    Be aware that by convention a named parameter starts with an @, however that is not really needed. 

    But I strongly recomend it. So Z becomes @Z then.


    Success Cor

    Monday, February 12, 2018 10:51 AM
  • Both replies provide you with that is needed, see the following for an example for working with a DataAdapter. 

    About the only downside with parameters is you can't see the full SQL statement with actual values so I created a language extension for this found here. If interested, click on the C# download link.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Monday, February 12, 2018 12:22 PM
    Moderator