WCF连接数据库
[ServiceContract]
public interface 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" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://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();
}
}
上一篇: python使用jieba实现中文分词去停用词方法示例
下一篇: python编写弹球游戏的实现代码