使用c#从SQL Server数据库读取数据

时间:2014-11-08 15:55:30

标签: sql-server ado.net

我有BuilderString的列表,我想要包含数据

 public  List<int> IDS = new List<int>();

 public List<StringBuilder> Items = new List<StringBuilder>(); 

这段代码出了什么问题?

SqlConnection con2 = new SqlConnection("Data Source=aya-PC\\SQLEXPRESS;Initial Catalog=ItemSet;Integrated Security=True");
SqlDataReader rdr2;
SqlCommand cmd2;

con2.Open();

for (int i = 0; i < IDS.Count; i++)
{
    cmd2 = new SqlCommand("select item From TransactiontData where idT=@IDS[i]", con2);
    cmd2.CommandType = CommandType.Text;
    rdr2 = cmd2.ExecuteReader();
    SqlParameter param = new SqlParameter();
    param.ParameterName = "@IDS[i]"

    while (rdr2.Read())
    {
        Items[i].Append((StringBuilder)rdr2["item"]);
    }
} 

2 个答案:

答案 0 :(得分:1)

您需要稍微重新排列代码:

using (SqlConnection con2 = new SqlConnection("Data Source=aya-PC\\SQLEXPRESS;Initial Catalog=ItemSet;Integrated Security=True"))
using (SqlCommand cmd2 = new SqlCommand("select item From TransactiontData where idT = @IDS", con2))
{
   // add the paramter to the command
   cmd2.Parameter.Add("@IDS", SqlDbType.Int);

   con2.Open();

   for (int i = 0; i < IDS.Count; i++)
   {
       // set the parameter value
       cmd2.Parameter["@IDS"].Value = IDS[i];

       // only *THEN* call ExecuteReader()
       using (SqlDataReader rdr2 = cmd2.ExecuteReader())
       {
              while (rdr2.Read())
              {
                  // **NOT SURE** what you're trying to do here.....
                  // First of all, you need to just call Items.Add()
                  // to add new items to the list - and I'm TOTALLY
                  // UNCLEAR what you're trying to do casting the reader
                  // value to a StringBuilder.......
                  // 
                  // Items[i].Append((StringBuilder)rdr2["item"]);
                  //
                  // replaced with what *might* make more sense.....
                  Items.Add(rdr2["item"].ToString());
              }

              rdr.Close();
       }
    }        

    con2.Close(); 
} 

注意事项:

  • 我建议始终SqlConnectionSqlCommandSqlDataReader放入using() {...}块,以确保妥善处置

  • 您需要添加参数并设置其值 BEFORE 您致电.ExecuteReader()

  • 由于查询本身永远不会改变 - 在每次迭代中创建新的SqlCommand都没有意义。创建命令一次 - 然后在每次迭代时设置参数(这是唯一改变的)

答案 1 :(得分:0)

您需要在应用程序代码中而不是在查询中分配参数值。通过将列值转换为StringBuilder,我不确定您要完成的是什么。假设每个StringBuilder项都包含从varchar / nvarchar列中检索的单个字符串,下面的示例将执行此操作。

 for (int i = 0; i < IDS.Count; i++)
 {
        var cmd2 = new SqlCommand("select item From TransactiontData where idT=@IDS", con2);

        SqlParameter param = new SqlParameter("@IDS", SqlDbType.Int) { Value = IDS[i] };

        var rdr2 = cmd2.ExecuteReader();

        while (rdr2.Read())
        {
            Items.Add(new StringBuilder((string)rdr2["item"]));
        }
 }