返回一个int而不是一个数据表

时间:2011-12-01 18:36:49

标签: c# sql datatable int data-access

如何更改下面的语法以返回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;

   }

4 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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();
}

答案 2 :(得分: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]); 

   } 

答案 3 :(得分:1)

而不是:

 return dt;

使用它:

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

声明还需要更改为:

 public int GetMemberID(string guid)