c#读取sql中的一个数值

例如studentI数据库中有student表,
表中有studentname和studentage两个属性,
textBox1中输入学生姓名,点击button1,
textBox2中输出学生年龄,应该怎么写?

//抱歉,手边没有编译器,但应该没问题!~
这是一种,我认为最简单:
conn.open();
sql="select studentage from student where studentname="+textBox1.text.trim();
sqlcommand cmd=new sqlcommand (sql,conn);
object i=cmd.executescalar();
textbox2.text=i.tostring();
conn.close();

楼上用的
using(SqlDataReader dr = cmd.ExecuteReader())
为二种方法,但没有关闭数据库

第三种是用 SqlDataAdapt
ex:
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
//填充数据
da.Fill(ds);
textbox2.text=ds.Table[0].Rows[0][0].ToString();

不要忘记关闭数据库!~
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-04-13
sql="select studentage from student where studentname="+textBox1.text.trim();

然后读取就可以了呀
第2个回答  2010-04-13
string sql=("select stuentage from student where studentname={0}",textBox1.text.trim());
第3个回答  2010-04-13
string sql=("select stuentage from student where studentname='{0}’",textBox1.text.trim());

补充上面的 字符串应该要加单引号
第4个回答  2010-04-13
以sqlserver为例,大概代码如下。
strSql="select studentage from student where studentname="+textBox1.text.trim(); //拼接sql语句(注:这不是最好的方式,会存在注入漏洞,但按你现问的这个问题,还没到要考虑这个漏洞的时候,只要会这么用就可以了)

SqlConnection connection = new SqlConnection("connectionString数据库连接串")
connection.open()
SqlCommand cmd = new SqlCommand(strSql,connection )//connection 为你创建的连接对象
using(SqlDataReader dr = cmd.ExecuteReader())
{

if(dr.Read())
{
textBox2=dr["studentage"].ToString();
}
}
还不明白可参考msdn帮助手册:http://msdn.microsoft.com/zh-cn/library/9kcbe65k(v=VS.80).aspx
第5个回答  2010-04-13
一楼二楼皆正解
相似回答
大家正在搜