WCF连接数据库
[html[ServiceContract]
public inte易做图ce IService1
{
//打开数据库
[OperationContract]
void openSql();
//关闭数据库
[OperationContract]
void closeSql();
//查询数据
[OperationContract]
DataSet querySql();
}
[html]
public class Service1 : IService1
{
//连接数据库
SqlConnection strCon = new SqlConnection("server=SQLServer服务器名称;database=数据库名称;uid=用户名;pwd=密码");
/// <summary>
/// 打开数据库
/// </summary>
/// <returns></returns>
public void openSql()
{
strCon.Open();
}
/// <summary>
/// 关闭数据库
/// </summary>
/// <returns></returns>
public void closeSql()
{
strCon.Close();
}
/// <summary>
/// 查询表TEST1中的数据
/// </summary>
/// <returns></returns>
public DataSet querySql()
{
try
{
openSql();
string strSql = "SELECT TNAME,TINTRO FROM TEST1";
DataSet ds = new DataSet();
SqlDataAdapter s = new SqlDataAdapter(strSql, strCon);
s.Fill(ds);
return ds;
}catch(Exception ex)
{
throw ex;
}finally{
closeSql();
}
}
}
[html]
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="getData.aspx.cs" Inherits="ShowData.getData" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
数据库的连接<br />
<br />
<asp:GridView ID="showData" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:BoundField DataField="TNAME" HeaderText="公司名称" />
<asp:BoundField DataField="TINTRO" HeaderText="公司简介" />
</Columns>
</asp:GridView>
</form>
</body>
</html>
[html]
public partial class getData : System.Web.UI.Page
{
//实例化WCF服务端的类
host.Service1Client sql = new host.Service1Client();
protected void Page_Load(object sender, EventArgs e)
{
//把查询到的数据显示到GridView组件中去
showData.DataSource = sql.querySql();
showData.DataBind();
}
}
补充:Web开发 , ASP.Net ,