在WebService中增加操作数据库的方法。
在Web Service增加数据库操作类:DbAccess.cs
添加引用
using System.Data.SqlClient;
using System.Data;
具体代码如下
namespace WebServiceTest
{
public class DbAccess
{
private static SqlConnection cnn = new SqlConnection();
private static SqlCommand cmd = new SqlCommand();
private static SqlDataAdapter adapter = new SqlDataAdapter();
public SqlTransaction DbTran;
private static string strConn = “Data Source=(local);Initial Catalog=DemoTest;Integrated Security=True”;
private void CreteConn()
{
try
{
if (cnn.State != ConnectionState.Open)
{
cnn.ConnectionString = strConn;
cnn.Open();
}
}
catch (Exception ex)
{
throw ex;
}
}
public void readDataThroughAdapter(string query, DataTable dt)
{
try
{
if (cnn.State == 0)
{
CreteConn();
}
cmd.Connection = cnn;
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
}
catch (Exception ex)
{
throw ex;
}
}
}
在引用服务的App中使用该方法查询数据库中的数,并展示在UI上。
localhost.MyWebService myService = new localhost.MyWebService();
测试代码如下:
private void btnQuery_Click(object sender, RoutedEventArgs e)
{
int id = 0;
if (!int.TryParse(txtId.Text, out id))
{
return;
}
var result = myService.dataTableForUsers(id.ToString());
DataTable dt = JsonConvert.DeserializeObject(result);
dg.ItemsSource = dt.DefaultView;
}
效果如下:
数据库内容如下: