/// <summary>
/// Get UserName by UserID
/// </summary>
/// <returns>UserName</returns>
public string GetNamebyID(int id)
{
strSQL = "Select * from Users Where UserID='" + UserID + "'";
SqlConnection myCn = new SqlConnection(strConn);
myCn.Open();
SqlCommand myCmd = new SqlCommand(strSQL,myCn);
try
{
myCmd.ExecuteNonQuery();
SqlDataReader reader = myCmd.ExecuteReader();
if(reader.Read())
{
return(reader.GetString(1));
}
else
{
return "未知用户名";
}
}
catch(System.Data.SqlClient.SqlException e)
{
throw new Exception(e.Message);
}
finally
{
myCmd.Dispose();
myCn.Close();
}
}实际运行时总是走到
return "未知用户名";分支
为什么呢?
数据库结构:
UserID int 4 0
UserName varchar 50 1
Password varchar 50 1

解决方案 »

  1.   

    strSQL = "Select * from Users Where UserID=" + UserID;
      

  2.   

    运行时提示
    strSQL = "Select * from Users Where UserID=" + UserID;
    System.Exception: 第 1 行: '=' 附近有语法错误。
      

  3.   

    既执行myCmd.ExecuteNonQuery();有执行myCmd.ExecuteReader();你要干吗?
      

  4.   

    strSQL = "Select * from Users Where UserID="+ UserID;
      

  5.   


    public string GetNamebyID(int id)
    改成
    public string GetNamebyID(string UserID)
    试试
      

  6.   

    to:zhao606(奋)  我copy的代码,我把myCmd.ExecuteNonQuery();去掉了to:oasis_wen(十有八九) 
    这个不行,运行时错误: '=' 附近有语法错误。
      

  7.   

    你的strsql换成如下的语句看看:strSQL = "Select * from Users Where UserID='{0}'";
     strSQL=string.formate(strSQL,UserID);
      

  8.   

    代码已修改为: public string GetNamebyID(int id)
    {
    //strSQL = "Select * from Users Where UserID='" + UserID + "'";
    strSQL = "Select * from Users Where UserID="+ UserID;
    SqlConnection myCn = new SqlConnection(strConn);
    myCn.Open();
    SqlCommand myCmd = new SqlCommand(strSQL,myCn);
    try
    {
    //myCmd.ExecuteNonQuery();
    SqlDataReader reader = myCmd.ExecuteReader();
    if(reader.Read())
    {
    return(reader.GetString(1));
    }
    else
    {
    return "未知用户名";
    }
    }
    catch(System.Data.SqlClient.SqlException e)
    {
    throw new Exception(e.Message);
    }
    finally
    {
    myCmd.Dispose();
    myCn.Close();
    }
    }运行时错误: 
    strSQL = "Select * from Users Where UserID="+ UserID;'=' 附近有语法错误。
      

  9.   

    to:回复人: zhao606(奋) ( ) 信誉:100  2005-11-06 22:27:00  得分: 0  
     
     
       你的strsql换成如下的语句看看:strSQL = "Select * from Users Where UserID='{0}'";
     strSQL=string.formate(strSQL,UserID);  
     
    还是会走到else分支
      

  10.   


    public string GetNamebyID(int id)
    改成
    public string GetNamebyID(int UserID)
    试试
      

  11.   

    Select * from Users Where UserID="+ UserID该为
    Select * from Users Where UserID="+ id你函数传的是id,而不是UserID
      

  12.   

    ^_^  soft_biao(巴不豆)正解
    其它朋友也有分