【问题标题】:Can i get multiple data type records from sql to arraylist and get it in another form我可以从sql获取多个数据类型记录到arraylist并以另一种形式获取吗
【发布时间】:2019-02-26 15:12:27
【问题描述】:

我想在 arraylist 中获取我的任何表记录并以另一种形式获取它(无论循环有多少列将数据检索到 arraylist) 这是我的代码:

public static ArrayList getrecord(String Table, String Column, Int32 id)
{
    ArrayList asd = new ArrayList();
    Form1.con.Close();
    Form1.con.Open();
    SqlCommand sq = new SqlCommand("Select * from " + Table + " where " + Column + " = " + id, Form1.con);
    SqlDataReader sdr = sq.ExecuteReader();
    if (sdr != null)
    {
        while (sdr.Read())
        {
            for(int i =0; i < sdr.FieldCount; i++)
            {
                asd.Add(sdr.GetValue(i).ToString());
            }
        }
    }
    return asd;
}

【问题讨论】:

  • 这里有很多不好的地方。首先是对 sql 注入开放。这根本不是处理查询的正确方法。其次,您有一个通用方法可以从任何表中获取一行。这是数据,不是通用的。您必须使用 select * 这意味着您几乎总是会返回大量您实际上不需要的数据。从长远来看,这里的安全和性能问题会给你带来很多痛苦。我会考虑完全重新思考这是如何工作的。
  • 比@SeanLange 先生,您能指导我一个好方法吗,实际上我已经为所有查询创建了一个类,并通过单击按钮调用表单中的每个方法。所以我该怎么做?我应该在按钮点击功能中查询吗??
  • 不确定你的意思。您从查询数据的方式跳到了调用它的位置。您应该创建从数据库中检索数据的过程。当您需要数据时,您可以在代码中调用它们。但看在上帝的份上,不要使用这种通用的数据获取方法。
  • @SeanLange 请帮帮我,我想为此创建存储过程,所以你能给我代码如何使用此查询的参数创建 st_procedure
  • 我已经创建了这个程序

标签: c# arrays sql-server winforms arraylist


【解决方案1】:

我建议使用 DataTable 而不是 ArrayList。您可以用您需要的所有记录填充 DataTable 并在其他表单中使用它。

System.Data.SqlClient.SqlCommand sq = new System.Data.SqlClient.SqlCommand("your sql query", "your connection string");
System.Data.DataTable dt = new System.Data.DataTable();
System.Data.SqlClient.SqlDataAdapter sda = new System.Data.SqlClient.SqlDataAdapter(sq);
sda.Fill(dt);

【讨论】:

  • 在方法中我必须使用哪种数据类型来获取另一种形式的数据
  • foreach(dt.Rows 中的 DataRow 行){ string x = row["ColumnName"].ToString(); int y = int.Parse(row["AnotherColumnName"].ToString()); }
  • 它没有将行从一个类传递到另一种形式
猜你喜欢
  • 2013-09-25
  • 1970-01-01
  • 1970-01-01
  • 2014-07-25
  • 2016-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多