SQL CE 3.5 - Writing to a database

旧城冷巷雨未停 提交于 2019-12-11 16:23:36

问题


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();

  string 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();
  }
}

回答1:


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();
        }
    }



回答2:


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.



来源:https://stackoverflow.com/questions/3366123/sql-ce-3-5-writing-to-a-database

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