vs2010开发c#WebService访问SqlServer数据库

标签:
vs2010开发cwebservice访问sqlserver数据库 |
分类: 代码天地 |
一 开发环境
操作系统:Win7 64位
数据库:Sql Server2008 R2
服务器端:VS2010
配置IIS服务
IE 浏览器
二 数据库设计
创建数据库BOOK, 表 user, 字段和内容
如下:
id
name
age
1 李芳
18
2 王苗
20
3 王永
23
三 服务器端程序(C# WebService)
使用VS2010 编写服务端的C# WebService 提供服务,供其它应用访问。
(一).
新建一个Webservice项目

(二) 在VS中连接数据库
1. 菜单 视图 -- 服务器资源管理器 -- 右击 数据连接 ->
添加连接

2. 配置数据连接
(1). 点击 数据源 后面的更改 选择Microsoft
Sqlserver,返回
(2). 点击 服务器 后面的刷新 从中选择或输入自己的计算机名称
(3). 登录服务器 两种方式 均可
(4). 选择 或输入一个数据名,选刚建的 book
(5). 点击 测试连接 直到 检测连接成功,点击确定返回

到此就可以在VS中查看和编辑数据库
3. 查到连接的字符串
Data Source=DELL-PC-15;Initial Catalog=BOOK;Integrated
Security=True

(三) 在VS中相关代码
1 创建 操作数据库的类

代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Text.RegularExp ressions;
using System.Collections;
using System.Collections.Generic;
namespace WebApplication1
{
}
2 Service1.asmx.cs如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using MyProject;
namespace WebApplication1
{
}
3 菜单 生成 -- 生成
WebApplication1
直到没有错误
4 在VS2010中 运行 程序

支持下列操作。有关正式定义,请查看服务说明。
HelloWorld
selectAllUser
查看所有用户

5 点击 selectAllUser
转到 浏览器
http://localhost:19143/WebService1.asmx?op=selectAllUser

6 点击 调用
转到 浏览器
http://localhost:19143/WebService1.asmx/selectAllUser
This XML file does not appear to have any style information
associated with it. The document tree is shown below.
<ArrayOfString
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://tempuri.org/">
<string>1</string>
<string>李芳</string>
<string>18</string>
<string>2</string>
<string>王苗</string>
<string>20</string>
<string>3</string>
<string>王永</string>
<string>30</string>
</ArrayOfString>
到此 WebService 连接 Sql Server数据库成功

7 发布程序
菜单 生成 -- 发布
WebApplication1
发布方法 选择 文件系统
目标位置 选择一个自己的文件夹 比如 d:\MyWebService
点击 发布 ,直到提示发布成功即可

四 网站部署
1 IIS设置
2 新建网站
3 入站规则
五 在浏览器中测试
1 本机访问
http://localhost:8060/WebService1.asmx
2 外机访问 需要输入你的IP 地址或者计算机名称
右击 计算机 -- 属性--- 看到你的计算机名,比如dell-pc-15
http://dell-pc-15:8060/WebService1.asmx
http://10.3.1.73:8060/WebService1.asmx
六 附录
1 有关的创建调试部署参见
2 有关IIS 设置