gpt4 book ai didi

c# - 为什么我无法通过对表执行第二个查询来将第二个结果添加到列表框? SQL

转载 作者:行者123 更新时间:2023-11-29 12:20:20 25 4
gpt4 key购买 nike

我遇到这个错误是因为我想通过对每个整数进行计数来打印出同一电影名称中的所有 5 个不同的评级整数。第一个查询执行得非常完美,但为什么由于出现如下错误而无法使第二个查询正常工作?

错误:{“列‘RatingNum2’不属于表 Table。”}

   private void EachRating_Click(object sender, EventArgs e)
{
string filename, connectionInfo;
SqlConnection db;

this.listBox1.Items.Clear();

filename = "netflix.mdf";

connectionInfo = String.Format(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=
|DataDirectory|\{0};Integrated Security=True;", filename);

string moviename = this.textBox1.Text;
moviename = moviename.Replace("'", "''");

string five = "5";
string four = "4";

db = new SqlConnection(connectionInfo);
db.Open();

SqlCommand cmd = new SqlCommand();
cmd.Connection = db;

cmd.CommandText = string.Format(
@"
SELECT MovieName, RatingNum1 FROM Movies
INNER JOIN
(
SELECT MovieID, Count(Rating) as RatingNum1 FROM Reviews
WHERE Rating = 5
GROUP BY MovieID
)TEMP
ON TEMP.MovieID = Movies.MovieID
WHERE MovieName = '{0}';", moviename);

SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);

DataTable dt = ds.Tables["TABLE"];

foreach (DataRow row in dt.Rows)
{
string msg = string.Format("{0}: {1}",
five.ToString(),
row["RatingNum1"].ToString());

this.listBox1.Items.Add(msg);
}

SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = db;

cmd2.CommandText = string.Format(
@"
SELECT MovieName, RatingNum2 FROM Movies
INNER JOIN
(
SELECT MovieID, Count(Rating) as RatingNum2 FROM Reviews
WHERE Rating = 4
GROUP BY MovieID
)TEMP
ON TEMP.MovieID = Movies.MovieID
WHERE MovieName = '{0}'", moviename);

SqlDataAdapter adapter2 = new SqlDataAdapter(cmd2);
DataSet ds2 = new DataSet();
adapter.Fill(ds2);

DataTable dt2 = ds2.Tables["TABLE"];

foreach (DataRow row2 in dt2.Rows)
{
string msg = string.Format("{0}: {1}",
four.ToString(),
row2["RatingNum2"].ToString()); //gets the error

this.listBox1.Items.Add(msg);
}

最佳答案

您正在使用第一个适配器填充第二个数据集,因此数据表无法找到“RatingNum2”列。

adapter.Fill(ds2);

应该是

adapter2.Fill(ds2);

关于c# - 为什么我无法通过对表执行第二个查询来将第二个结果添加到列表框? SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29113930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com