日期:2014-05-18  浏览次数:21195 次

急急急!!在线等,c#如何把数据库查询语句的值读出来赋给变量
数据库查询语句为:
string strsql6 = "select count(sno) from student where cno='" + class1 + "' and cet4>425";
想把查询后的值赋给TextBox;

------解决方案--------------------
C# code

Sqlcommond cmd =new Sqlcommond();
textBox.Text=cmd.ExecuteScalar().ToString();

------解决方案--------------------
C# code

using System.Data.SqlClient;

using(SqlConnection con = new SqlConnection("Data Source=.;uid=sa;pwd=sa;Database=Northwind"))
{
    con.Open();
    string strsql6 = "select count(sno) from student where cno='" + class1 + "' and cet4>425";
    SqlCommand cmd = new SqlCommand(strsql6,con);
     this.TextBox1.Text = cmd.ExecuteScalar().ToString();
}

------解决方案--------------------
探讨
C# code


using System.Data.SqlClient;

using(SqlConnection con = new SqlConnection("Data Source=.;uid=sa;pwd=sa;Database=Northwind"))
{
con.Open();
string strsql6 = "select count(sno)……

------解决方案--------------------
楼上的只针对了楼主的例子情况,多字段的话,要参考ExecuteReader或者用SqlAdapter的fill方法,装到DataTable里面,然后写for循环,table.Rows[i]["字段名"].ToString()可以读取字段的值
------解决方案--------------------
探讨

C# code

using System.Data.SqlClient;

using(SqlConnection con = new SqlConnection("Data Source=.;uid=sa;pwd=sa;Database=Northwind"))
{
con.Open();
string strsql6 = "select count(sno) from s……

------解决方案--------------------
C# code

using System.Data.SqlClient;

using(SqlConnection con = new SqlConnection("Data Source=.;initial catalog=Northwind;user id=sa;password=sa"))
{
    string strsql6 = "select count(sno) from student where cno=@class1 and cet4>425";
    using(SqlCommand cmd = new SqlCommand(strsql6,con))
  { 
     con.Open();
     cmd.Parameters.AddWithValue("@class1",class1);     
     this.TextBox1.Text = cmd.ExecuteScalar().ToString();
  }
}