2009-01-14 92 views
0

我該如何重構這個讓它返回一個字符串而不是數據集?返回webmethod中的字符串而不是數據集。

[WebMethod] 
public DataSet GetPONumber(string Database) 
{ 
    SqlConnection sqlConn = new SqlConnection(); 

    sqlConn.ConnectionString = GetConnString(Database); 

    // build query 
    string strSQL = @" A SELECT QUERY!!!!! "; 

    SqlDataAdapter da = new SqlDataAdapter(strSQL, sqlConn); 
    DataSet ds = new DataSet(); 
    da.Fill(ds, "NEWPO"); 

    return (ds); 
} 

回答

0

這是我finnished與和工作,感謝您的輸入:

[WebMethod] 
    public String GetPONumber(string Database) 
    { 
     //Create Object ready for Value 
     object po = ""; 

     //Set Connection 
     SqlConnection Connection = new SqlConnection(GetConnString(Database)); 

     //Open Connection 
     Connection.Open(); 

     //Set Query to string 
     string Query = @" SQL QUERY GOES HERE!!!! "; 

     //Run Query 
     SqlCommand Command = new SqlCommand(Query, Connection); 

     //Set Value from Query 
     try 
     { 
      po = Command.ExecuteScalar(); 
     } 
     catch 
     { 
      //Error 
     } 

     //Clean up sql 
     Command.Dispose(); 
     Command = null; 


     //Clean up connection 
     Connection.Close(); 
     Connection.Dispose(); 
     Connection = null; 

     //Return Value 
     return po.ToString(); 
    } 
1

您可以將數據集轉換爲其JSON字符串表示形式。這樣,基本上任何客戶都可以輕鬆使用它。

1

您可以返回ds.GetXml()並更改返回類型。

這會將數據作爲XML返回。

如果你的結果很簡單(說一個單一的值),你可能只是想直接返回它們。

+0

這種情況下的值只返回一個單一值,您能否顯示完整的示例? – MartGriff 2009-01-14 15:51:25

1
//Use an SqlCommand and the ExecuteScalar method. 
//Cast returnValue to known object. 
SqlCommand command = sqlConn.CreateCommand(); 
command.CommandType = CommandType.Text; 
command.CommandText = @" A SELECT QUERY!!!!! "; 
sqlConn.Open(); 
object returnValue = command.ExecuteScalar(); 
command.Dispose(); 
return returnValue.ToString(); 
0

@MartGrif

我已經修改了代碼,包括使用的語句,這是常見的用法。它也使代碼更簡潔,我相信,更具可讀性。 using語句在代碼塊的末尾自動處理對象。請參閱文檔MSDN here

[WebMethod] 
public String GetPONumber(string Database) 
{ 
    //Create Object ready for Value 
    object po = ""; 

    //Set Connection 
    using(SqlConnection connection = new SqlConnection(GetConnString(Database))) 
    { 
     string Query = @" SQL QUERY GOES HERE!!!! "; 
     using(SqlCommand command = new SqlCommand(Query, connection)) 
     { 
      try 
      { 
       connection.Open(); 
       po = Command.ExecuteScalar(); 
      } 
      catch 
      { 
       //Error 
      } 
     } 
    } 
    return po.ToString(); 
} 
相關問題