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

从数据库中查询数据后赋给字符串问题
public string CheckDataYear(string logid)
{
string connect = "User ID=appDB;Initial Catalog=appDB;Data Source=LJJ;Password=appDB123";
SqlConnection con = new SqlConnection(connect);
con.Open();
string sql= "select jyrqy from t_tzsb_ylss_ys1_new where djid='logid'";
SqlCommand com = new SqlCommand(sql,con);
string year = com.ExecuteScalar().Tostring;//出错
  return year;
  }

我想把查询结果赋给一个字符串,为什么不可以啊



------解决方案--------------------
不过要想让连接能够即时关闭,最好使用using
如下
C# code

public string CheckDataYear(string logid) 
{
  string year="";
  string connect = "User ID=appDB;Initial Catalog=appDB;Data Source=LJJ;Password=appDB123"; 
  using(SqlConnection con = new SqlConnection(connect)){ 
    con.Open(); 
    string sql= "select jyrqy from t_tzsb_ylss_ys1_new where djid='logid'"; 
    SqlCommand com = new SqlCommand(sql,con);
    SqlDataReader rd=com.ExecuteReader();
    if(rd.read()){
      year = rd["字段名"].ToString();//出错 
     }
  }
    return year; 
}

------解决方案--------------------
string year = com.ExecuteScalar().Tostring;//出错 
是 ToString()
------解决方案--------------------
string year = com.ExecuteScalar().Tostring;//出错 
确定这个地方返回的值不是null?

------解决方案--------------------
探讨
不过要想让连接能够即时关闭,最好使用using
如下

C# code
public string CheckDataYear(string logid)
{
string year="";
string connect = "User ID=appDB;Initial Catalog=appDB;Data Source=LJJ;Password=appDB123";
using(SqlConnection con = new SqlConnection(connect)){
con.Open();
string sql= "select jyrqy from t_tzsb_ylss_ys1_new where djid='logid'";
SqlCommand com = n…