我如何重构它以使其返回字符串而不是数据集?
[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 :(得分:1)
您可以将数据集转换为其JSON字符串表示形式。这样,基本上任何客户都可以轻松使用它。
答案 1 :(得分:1)
您可以返回ds.GetXml()并更改返回类型。
那会将数据作为XML返回。
如果你的结果非常简单(说一个单一的值),你可能只想直接返回它们。
答案 2 :(得分: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();
答案 3 :(得分:0)
这就是我完成的工作,感谢您的意见:
[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();
}
答案 4 :(得分:0)
@MartGrif
我已修改您的代码以包含using语句,这是常见的用法。它还使代码更简洁,我相信,更具可读性。 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();
}