将数据集作为方法中的对象返回

时间:2012-07-22 06:04:16

标签: c# asp.net sql-server

我正在编写一个方法来查询表并返回包含指定列的 Dataset 对象。此外,我的用户名和问题有问题。密码,所以我使用 Windows 身份验证相同,但我在我写的代码片段中对此不太确定。

 protected void GetProgramList()
    {
        SqlConnection cn = new SqlConnection("server=Daffodils-PC/sqlexpress;Database=Assignment1;Trusted_Connection=Yes;");
        SqlCommand cmd = new SqlCommand("SELECT ProgramName FROM Program", cn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet1 ds1 = new DataSet1();

    }

我一直在尝试遵循官方的MS文档,但我不确定我要去哪里?有人可以通过一些链接或片段来帮助我吗?

4 个答案:

答案 0 :(得分:7)

我想说你有两个选择: 1.创建一个DataSet类变量,因此可以从整个类访问它的引用(将其访问修饰符设置为public,以便可以从其他类访问它) 2.或创建一个返回类型为DataSet的方法。但在这种情况下,另一方面也必须设置为接收DataSet:

// 2。溶液:

    private void GetData()
    {
        //from inside some method:
        DataSet ds = GetProgramList();
    }

    protected DataSet GetProgramList()
    {
        DataSet ds1 = new DataSet();
        using (SqlConnection cn = new SqlConnection("server=Daffodils-PC/sqlexpress;Database=Assignment1;Trusted_Connection=Yes;"))
        {
            using (SqlDataAdapter da = new SqlDataAdapter(@"SELECT ProgramName FROM Program", cn))
                da.Fill(ds1, "TableName1");
        }
        return ds1;
    }
    //


//1. solution:
class YourClass
{
    DataSet ds1;
    protected void GetProgramList()
    {
        SqlConnection cn = new SqlConnection("server=Daffodils-PC/sqlexpress;Database=Assignment1;Trusted_Connection=Yes;");
        SqlCommand cmd = new SqlCommand("SELECT ProgramName FROM Program", cn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        ds1 = new DataSet();
    }
}

答案 1 :(得分:2)

将您的连接字符串放在app.config或web.config

中的AppSettings部分
   public string GetSqlConnection()
    {
        return  System.Configuration.ConfigurationManager.AppSettings["SqlConnectionString"];
    }



  public DataSet getDataSet(string sql)
    {
        DataSet ds = new DataSet();
        SqlConnection conn = new SqlConnection(GetSqlConnection());
        SqlDataAdapter da = new SqlDataAdapter(sql, conn);
        da.Fill(ds);
        conn.Close();
        conn.Dispose();
        da.Dispose();
        return ds;
    }

答案 2 :(得分:0)

建议:“使用”System.Data和System.Data.SqlClient,并使用“SqlDataReader”:

读取例程中的所有内容(通常是首选),或者将SqlDataReader传递回调用者(作为函数返回)。

请务必。完成后关闭()读者:)

答案 3 :(得分:0)

SQLDataAdapter basic将帮助您开始创建连接并在代码中使用它的基础知识。

相关问题