/// <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
/// 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
strSQL = "Select * from Users Where UserID=" + UserID;
System.Exception: 第 1 行: '=' 附近有语法错误。
public string GetNamebyID(int id)
改成
public string GetNamebyID(string UserID)
试试
这个不行,运行时错误: '=' 附近有语法错误。
strSQL=string.formate(strSQL,UserID);
{
//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;'=' 附近有语法错误。
你的strsql换成如下的语句看看:strSQL = "Select * from Users Where UserID='{0}'";
strSQL=string.formate(strSQL,UserID);
还是会走到else分支
public string GetNamebyID(int id)
改成
public string GetNamebyID(int UserID)
试试
Select * from Users Where UserID="+ id你函数传的是id,而不是UserID
其它朋友也有分