合并三个表时出错

时间:2013-03-10 14:40:37

标签: c#

我遇到错误“对象引用没有设置为对象的实例。”

 // Define the ADO.NET objects.
        SqlConnection con = new SqlConnection(connectionString);
        string selectSQL = "SELECT * FROM tbl_lecturer_project";
        SqlCommand cmd = new SqlCommand(selectSQL, con);
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        DataSet dsPubs = new DataSet();

        // Try to open database and read information.
        try
        {
            con.Open();
            adapter.Fill(dsPubs, "tbl_lecturer_project");

            // This command is still linked to the data adapter.
            cmd.CommandText = "SELECT * FROM tbl_student_project_choice";
            adapter.Fill(dsPubs, "tbl_student_project_choice");

            cmd.CommandText = "SELECT * FROM tbl_team";
            adapter.Fill(dsPubs, "tbl_team");

            DataRelation SCoiceLec = new DataRelation("SCoiceLec",  dsPubs.Tables["tbl_lecturer_project"].Columns["lecturerProjectId"], dsPubs.Tables["student_project_choice"].Columns["choiceProjectId"]);
            DataRelation SChoiceNTeam = new DataRelation("SChoiceNTeam",dsPubs.Tables["student_project_choice"].Columns["choiceGroupId"], dsPubs.Tables["tbl_team"].Columns["teamId"]);

请帮忙。我想从所有3个表中检索数据。

1 个答案:

答案 0 :(得分:3)

您的代码存在许多问题。这是一个:

adapter.Fill(dsPubs, "tbl_lecturer_project");

应该是

adapter.Fill(dsPubs);

我认为你想要的是:

string selectSQL = @"SELECT * FROM tbl_lecturer_project;
                     SELECT * FROM tbl_student_project_choice;
                     SELECT * FROM tbl_team";

using(SqlConnection con = new SqlConnection(connectionString))
{
   con.Open();
   using(SqlCommand cmd = new SqlCommand(selectSQL, con))
   {
      using(SqlDataAdapter adapter = new SqlDataAdapter(cmd))
      {
         DataSet dsPubs = new DataSet();

         adapter.Fill(dsPubs);

         // use dataset.
      }
   }
}

这三个表的名称为TableTable1Table2