合并三个表时出错

本文关键字:出错 三个 合并 | 更新日期: 2023-09-27 18:03:07

我有一个错误"对象引用未设置为对象的实例。"

 // 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个表中检索数据

合并三个表时出错

您的代码有许多问题。这里有一个:

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