日期:2014-05-17  浏览次数:20397 次

C# 【求助】:数据库操作的一个问题!!!急!!!!详情如下:
用C#成功连接了数据库之后,然后用SqlCommand来执行一段Sql语句,我想这段SQL语句怎么和C#的变量联系起来?我举个例子吧:

   假设在数据库中国有一个R表,R表中字段为:name、id、classid、age。然后我通过C#成功连接到了这张表,那么:
       1、我想用SqlCommand命令来获取name、age:  在C#程序中定义:string StudentName;     int StudentAge ,然后我要执行Sql语句了:SqlCommmand cmd = new SqlCommand();  cmd.connection = conn; cmd.CommandText = "select name,age from age";   好了,请问如何让StudentName = name;   StudentAge = age;   呢?
 ☆☆☆2、我想如果当age>20时执行一个操作,当age<20时执行一个操作?怎样实现?应该怎么写语句?(当然这种情况下我是想不通过在C#程序中定义的int StudentAge来操作,如果用if(StudentAge>20){} else{}就不需要问了,我就是想知道直接通过Sql和C#程序可以实现吗?比如说:if("select age from R where Age>20" == true)这样类型的,当然这个语句是错的,这句只是我想更确切的表达一下用的)
------最佳解决方案--------------------
问题一   假设age为int型

SqlCommmand cmd = new SqlCommand();
cmd.connection = conn;
cmd.CommandText = "select name,age from age where name='"+StudentName+"' and age="+StudentAge; 

问题二
取数据的时候分别取age<20和age>20的数据集,然后在程序中分别处理,如age<20

SqlCommmand cmd = new SqlCommand();
cmd.connection = conn;
cmd.CommandText = "select name,age from age where age<20"; 

单独在程序中处理
------其他解决方案--------------------
我记得网上有的啊。 cmd.connection = conn; cmd.CommandText = "select name,age from age where StudentName ="+'"name"';   之类的格式来传变量的。但是很久没写我也不记得了。
第二个问题,还是用if else吧。还有,很多事情放到SQLServer里面做比较好,前端操作数据库毕竟不是强项。
------其他解决方案--------------------
 SqlDataReader dr = cmd.ExecuteReader();
                if (dr.HasRows)
                {
                    while (dr.Read())
                    {
                          //写代码
                    }
                }

------其他解决方案--------------------
非常感谢~谢谢~!