[英]Return String from a webmethod instead of a dataset.
How would I refactor this to get it to return a string not a dataset? 我将如何重构它使其返回字符串而不是数据集?
[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);
}
You could transform the dataset into its JSON string representation. 您可以将数据集转换为其JSON字符串表示形式。 This way it can be easily consumed by basically any client. 这样,基本上任何客户端都可以轻松使用它。
You could return ds.GetXml() and change the return type. 您可以返回ds.GetXml()并更改返回类型。
That would return the data as XML. 那将以XML返回数据。
If your results were quite simple (Say a single value), you might just want to return them directly. 如果您的结果非常简单(说一个值),则可能只想直接返回它们。
//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();
@MartGrif @MartGrif
I have modified your code to include the using statement, this is common usage. 我已经修改了您的代码以包含using语句,这是常见用法。 It also makes the code more terse and I believe, more readable. 这也使代码更简洁,我相信代码也更具可读性。 The using statement automatically disposes of object at the end of the code block. using语句自动将对象置于代码块的末尾。 See documentation on MSDN here 在此处查看有关MSDN的文档
[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();
}
This is what I finnished with and is working, thank you for your input: 这是我完成的工作,感谢您的投入:
[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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.