How to use SqlCeParameterCollection?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 05:42:16

问题


I wanna to know exactly how we do these thing on C# .NET 4.0 Form Application:

  • Declaring SqlCeParameterCollection Object
  • Adding Parameters to the collection
  • Add the Collection to the Command

Here are samples of my current code:

  • Declaring & Adding

    SqlCeParameterCollection Parameters = new SqlCeCommand().Parameters;
    Parameters.Add("username", Username);
    Parameters.Add("password", Password);
    

Now how to add this collection at once to the command?

Thanks


回答1:


Try this:

string query = "...(whatever you need).....";

using(SqlCeConnection conn = new SqlCeConnection(connectionString))
using(SqlCeCommand cmd = new SqlCeCommand(query, conn))
{ 
    // just add parameters directly to SqlCeCommand object .... 
    cmd.Parameters.Add("username", Username);
    cmd.Parameters.Add("password", Password);

    conn.Open();
    cmd.ExecuteNonQuery();  // or whatever you need to do 
    conn.Close();
}

If you must set up your parameters separately, up front, then you need to do something like this (since you cannot directly use SqlCeParameterCollection):

List<SqlCeParameters> parameters = new List<SqlCeParameters>();

parameters.Add(new SqlCeParameter(.....));
parameters.Add(new SqlCeParameter(.....));

string query = "...(whatever you need).....";

using(SqlCeConnection conn = new SqlCeConnection(connectionString))
using(SqlCeCommand cmd = new SqlCeCommand(query, conn))
{ 
    // add all parameters from the list - casting to an array
    cmd.Parameters.AddRange(parameters.ToArray());

    conn.Open();
    cmd.ExecuteNonQuery();  // or whatever you need to do 
    conn.Close();
}



回答2:


SqlCeCommand.Parameters is read only, so you won't be able to assign a new SqlParametersCollection directly to this property.

You typically want to use the CreateCommand factory method on SqlCeConnection to create the command (as it will link the connection for you).

Then you use the command.Parameters directly:

SqlCeCommand cmd = con.CreateCommand();
// cmd.CommandType = ...; cmd.CommandText = ...
cmd.Parameters.Add("username", Username);
cmd.Parameters.Add("password", Password);


来源:https://stackoverflow.com/questions/13062162/how-to-use-sqlceparametercollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!