我试图从字符串数组中添加多个值dateOperation typeOperation买入和卖出的数组长度相等
这是我尝试的核心,它可以工作但不是循环
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/taylor
但是这个带循环的代码片段并不是因为我在语法中遗漏了一些东西
using (SqlCeConnection connection = new SqlCeConnection(connectionString))
{
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO Operations (date, type, bought, sold) VALUES (@date, @type, @bought, @sold)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("@date", dateOperation[0]);
cmd.Parameters.AddWithValue("@type", typeOperation[0]);
cmd.Parameters.AddWithValue("@bought", bought[0]);
cmd.Parameters.AddWithValue("@sold", sold[0]);
connection.Open();
cmd.ExecuteNonQuery();
}
因为有时dateOperations,typeOperation,买入和卖出并不总是相同长度的数组代码工作正常但它给我一个错误,如果数组小于4长度表收到数据罚款,但错误是拧我的程序如何解决它或如何做出异常 "参数化查询需要一个未提供的参数值。"
using (SqlCeConnection connection = new SqlCeConnection(connectionString))
{
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO Operations (date, type, bought, sold) VALUES (@date, @type, @bought, @sold)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
for (int i = 0; i <= bought.Length; i++)
{
cmd.Parameters.AddWithValue("@date", dateOperation[i]);
cmd.Parameters.AddWithValue("@type", typeOperation[i]);
cmd.Parameters.AddWithValue("@bought", bought[i]);
cmd.Parameters.AddWithValue("@sold", sold[i]);
}
connection.Open();
cmd.ExecuteNonQuery();
}
答案 0 :(得分:1)
首先需要在命令中添加参数(在循环之前)。然后在循环中设置参数的值并执行命令:
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO Operations (date, type, bought, sold) VALUES (@date, @type, @bought, @sold)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.Add("@date", DbType.DateTime);
// other parameters
connection.Open();
for (int i = 0; i <= bought.Length; i++)
{
cmd.Parameters["@date"].Value = dateOperation[i];
// other parameters
cmd.ExecuteNonQuery();
}