2011-12-01 76 views
-1

如何更改下面的语法以返回Int而不是数据表。我不需要一个datatable它只是一个值,将在查询中返回。这是整个数据访问的新事物。谢谢你的帮助。的返回int而不是数据表

public DataTable GetMemberID(string guid) 
    { 
     string strConectionString = ConfigurationManager.AppSettings["DataBaseConnection"]; 

     //set up sql 
     string StrSql = "SELECT MemberID FROM MEMBERS WHERE (Guid = @GuidID)"; 

     DataTable dt = new DataTable(); 
     using (SqlDataAdapter daObj = new SqlDataAdapter(StrSql, strConectionString)) 
     { 
      daObj.SelectCommand.Parameters.Add("@GuidID", SqlDbType.Int); 
      daObj.SelectCommand.Parameters["@GuidID"].Value = guid; 
      //fill data table 
      daObj.Fill(dt); 
     } 
     return dt; 

    } 
+1

我很好奇,为什么人们downvoting这个问题。 –

+2

这个问题很不明确。 – lesderid

+1

不清楚以什么方式? –

回答

2
public int GetMemberID(string guid) 
    { 
     string strConectionString = ConfigurationManager.AppSettings["DataBaseConnection"]; 

     //set up sql 
     string StrSql = "SELECT MemberID FROM MEMBERS WHERE (Guid = @GuidID)"; 

     DataTable dt = new DataTable(); 
     using (SqlDataAdapter daObj = new SqlDataAdapter(StrSql, strConectionString)) 
     { 
      daObj.SelectCommand.Parameters.Add("@GuidID", SqlDbType.Int); 
      daObj.SelectCommand.Parameters["@GuidID"].Value = guid; 
      //fill data table 
      daObj.Fill(dt); 
     } 
     return Convert.ToInt32(dt["MemberID"][0]); 

    } 
+2

请注意,我只修改你的上面的代码来返回一个int,而不是一个数据表。一种更简洁,更轻量级的方式来重构这个方法,就是切换到使用SqlCommand.ExecuteScalar()函数,该函数专门设计为仅返回一个值,而不是整个DataTable。 –

1

代替:

return dt; 

使用本:

if (dt.rows.count > 0) 
    return (int)dt.rows[0][0]; 

宣言还需要改为:

public int GetMemberID(string guid) 
3

使用SqlCommandExecuteScalar,而不是填充DataTable

string StrSql = "SELECT MemberID FROM MEMBERS WHERE (Guid = @GuidID)"; 
using(var cmd = new SqlCommand(sql, connection)) 
{ 
    cmd.Parameters.Add("@GuidID", SqlDbType.Int).Value = guid; 
    return (int)cmd.ExecuteScalar(); 
} 
4

可以使用SqlCommand代替SqlDataAdapter

int memberId = 0; 
using (var connection = new SqlConnection(conectionString)) 
using (var command = new SqlCommand(StrSql, connection)) 
{ 
    command.Parameters.Add("@GuidID", SqlDbType.Int).Value = guid; 
    memberId = (int) command.ExecuteScalar(); 
} 

return memberId; 
+0

也许它只是一个示例代码,但你的参数“guid”不是int。我可能会怀疑它不是一个字符串。如果它真的是一个指导,那就传递它 - 或重命名它。 –

+0

...并且,你可能会喜欢使用“Parameters.AddWithValue(...)”,它将添加一个参数,该参数的类型取决于任何值(在你的情况下,一个字符串)。 –

相关问题