我是网络搜索新手。我不知道如何在Web服务中编写程序请帮帮我 在程序中我想将Web服务连接到数据库,然后从那里我得到json格式的数据
在客户端我使用jquery移动框架,jquery Ajax
假设在数据库中
id title
1 asd
2 asw
答案 0 :(得分:1)
这是我从我的一些代码中复制的一个例子。
WCF界面定义
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
[ServiceContract]
public interface IGraphDataProvider
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "devices")]
List<string> get_devices();
}
WCF实施
public class GraphDataProvider : IGraphDataProvider
{
/**
* @brief Return a (possibly empty) list of devices listed in the configuration DB
* */
public List<string> get_devices()
{
// If you want to modify your headers...
// WebOperationContext.Current.OutgoingResponse.Headers["Access-Control-Allow-Origin"] = "*";
// Now just return a list of strings, WCF will convert to JSON
return getDevices();
}
}
负责JSON响应。如果您不知道如何阅读SQL DB,有几种方法。
您可以使用Entity Framework。这很简单方便,一旦你设置完你的代码就会像:
public static List<string> getDevices()
{
var db_context= new CfgEntities();
var devices = from row in db_context.Devices
where !row.Device.StartsWith("#")
select row.Device.Trim();
return devices.Distinct().ToList();
}
使用Microsoft的SQL Client。您的代码将如下所示:
using System.Data.SqlClient;
// ...
public static List<string> getDevices()
{
var sql_connection_ = new SqlConnection();
sql_connection_.ConnectionString = string.Format("Server=localhost; database={0}; Trusted_Connection=SSPI", dbName);
try
{
sql_connection_.Open();
}
// catch exceptions etc. If Open() worked then you have a connection.
string queryString = "SELECT [Device] from [Config].[dbo].[Devices]";
// Now I'm just copying shamelessly from MSDN...
SqlCommand command = new SqlCommand(queryString, sql_connection_);
SqlDataReader reader = command.ExecuteReader();
List<string> return_list = new List<string>();
while (reader.Read())
{
return_list.Add((string)reader[0]);
}
return return_list;
}