开发者

SQL CE 3.5 - Writing to a database

I'm trying to write to a data base, I have been working of the following site. In particular the LoadARow function.

I have been getting the runtime error

"System.IndexOutOfRangeException: A SqlCeParameter with ParameterName 'Value' is not contained by this SqlCeParamaterCollection.

The error references the line "command.Parameters["@Value"].Value = num;". The database I'm using has a Value column set as the key, and a text column.

using (SqlCeConnection connect = new SqlCeConnection("Data Source=C:\\Users\\mike\\Documents\\database.sdf"))
{
  connect.Open();

  strin开发者_运维百科g text = "test";
  int num = 0;

  using (SqlCeCommand command = new SqlCeCommand("insert into Data Table values (@Value, @Text)", connect))
  {
    command.Parameters.Add("@Text", SqlDbType.NVarChar);
    command.Parameters["@Value"].Value = num;
    command.Parameters.AddWithValue("@Text", text);
    command.ExecuteNonQuery();
  }
}


Try :

using (SqlCeConnection connect = new SqlCeConnection("Data Source=C:\\Users\\mike\\Documents\\database.sdf"))
    {
        connect.Open();

        string text = "test";
        int num = 0;

        using (SqlCeCommand command = new SqlCeCommand("insert into Data Table values (@Value, @Text)", connect))
        {
           command.Parameters.Add("@Value", SqlDbType.NVarChar, num);
           command.Parameters.Add("@Text", SqlDbType.NVarChar, text);
           command.ExecuteNonQuery();
        }
    }


The line:

command.Parameters.Add("@Text", SqlDbType.NVarChar); 

should read:

command.Parameters.Add("@Value", SqlDbType.NVarChar); 

You have not yet defined the variable at that point, which is why the next line errored out of index. A typo, I'm sure, since you defined @Text the line afterwards.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜