数据库查询和datagridview [英] database query and datagridview

查看:72
本文介绍了数据库查询和datagridview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好b $ b

我想知道在特定课程中注册的学生总数,其ID在DGVC.Rows [r] .Cells [c]中。



我尝试过这段代码,它应该在messagebox中显示1,因为一个学生注册了该课程,但它给出-1。我该怎么办?



Hi
I want to know total number of students registered in a particular course whose ID is in "DGVC.Rows[r].Cells[c]".

I've tried this code,it should show 1 in messagebox,as one student is registered to the course, but it gives -1. what shoud i do?

Connection cc = new Connection();
cc.con.Open();

SqlCommand cmdC = new SqlCommand("Select Count(*) from UCK_Scheduler..COURSE_REGISTRATION inner join UCK_Scheduler..STUDENT on COURSE_REGISTRATION.StudentID=STUDENT.StudentID where CourseID='" + DGVC.Rows[r].Cells[c].Value.ToString() + "' ", cc.con);

int cn = cmdC.ExecuteNonQuery();
MessageBox.Show(cn.ToString());
cc.con.Close();

推荐答案

你正在使用 ExecuteNonQuery 选择方法。这是错误的,因为 ExecuteNonQuery 用于插入/更新/删除记录。在您的情况下,由于您正在检索单个列,因此您可以使用 ExecuteScalar 来检索第一列第一行中找到的项目。



在此进一步阅读:

ExecuteNonQuery

ExecuteScalar

ExecuteNonQuery和ExecuteScalar之间的比较
You're using the ExecuteNonQuery method to select. That is wrong because ExecuteNonQuery is used to insert/update/delete records. In your case, since you're retrieving a single column, you can use ExecuteScalar which retrieves the item found in the first row from the first column.

Further reading here:
ExecuteNonQuery
ExecuteScalar
Comparision between ExecuteNonQuery and ExecuteScalar


如果 CourseID 整数字段,然后你需要修改下面的查询,不包括额外的单引号。

If CourseID is Integer field, then you need to modify the query like below excluding extra single quote.
SqlCommand cmdC = new SqlCommand("Select Count(*) from UCK_Scheduler..COURSE_REGISTRATION inner join UCK_Scheduler..STUDENT on COURSE_REGISTRATION.StudentID=STUDENT.StudentID where CourseID=" + DGVC.Rows[r].Cells[c].Value.ToString() + "", cc.con);





请调试代码并查看运行时查询的值。然后将查询带到 SQL Management Studio 并运行它。你可以看到错误,如果有的话。



Please debug you code and see what is the value of the query at runtime. Then take the query to SQL Management Studio and run it. You can see the errors, if any.


你应该使用ExecuteScalar()而不是ExecuteNonQuery()



我们使用EXcuteReader( )和ExcuteScalar()用于获取操作和

ExcuteNonQuery()用于更新和删除操作,
you should use ExecuteScalar() not ExecuteNonQuery()

we use EXcuteReader() and ExcuteScalar() for fetch operations and
ExcuteNonQuery() for update and delete operations,


这篇关于数据库查询和datagridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆