c# winform通过本地WebService接口访问SQL数据库实例

总体思路如下:先建立数据库,再建立webservice,最后通过winform的按钮来调用服务,达到操作数据库的目的。

1.数据库设计

数据库名称:sa ,表名称:C

在sql sever2008 R2下建立表与字段等。



2.建立webservice 

2.1启动vs2013,文件》新建项目》选择asp.net web 服务应用程序。





2.2默认按F5 Debug,浏览器自动生成Hello word的页面,表示ws配置成功。




2.3视图》服务器资源管理器》数据连接》添加连接数据库




2.4添加一个类,命名为DBOperation.cs



DBOperation.cs


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.RegularExpressions;
using System.Collections;
using System.Collections.Generic;

namespace WebServiceTest
{
    public class DBOperation : IDisposable
    {
        public static SqlConnection sqlCon;  //用于连接数据库  

        //将下面的引号之间的内容换成上面记录下的属性中的连接字符串  
        private String ConServerStr = @"Data Source=USER-20160715YA;Initial Catalog=sa;Integrated Security=True";

        //默认构造函数  
        public DBOperation()
        {
            if (sqlCon == null)
            {
                sqlCon = new SqlConnection();
                sqlCon.ConnectionString = ConServerStr;
                sqlCon.Open();
            }
        }

        //关闭/销毁函数,相当于Close()  
        public void Dispose()
        {
            if (sqlCon != null)
            {
                sqlCon.Close();
                sqlCon = null;
            }
        }

        /// <summary>  
        /// 获取所有货物的信息  
        /// </summary>  
        /// <returns>所有货物信息</returns>  
        public List<string> selectAllCargoInfor()
        {
            List<string> list = new List<string>();
            try
            {
                string sql = "select * from C";
                SqlCommand cmd = new SqlCommand(sql, sqlCon);
                SqlDataReader reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    //将结果集信息添加到返回向量中  
                    list.Add(reader[0].ToString());
                    list.Add(reader[1].ToString());
                    list.Add(reader[2].ToString());
                }

                reader.Close();
                cmd.Dispose();

            }
            catch (Exception)
            {

            }
            return list;
        }

        /// <summary>  
        /// 增加一条货物信息  
        /// </summary>  
        /// <param name="Cname">货物名称</param>  
        /// <param name="Cnum">货物数量</param>  
        public bool insertCargoInfo(string Cname, int Cnum)
        {
            try
            {
                string sql = "insert into C (Cname,Cnum) values ('" + Cname + "'," + Cnum + ")";
                SqlCommand cmd = new SqlCommand(sql, sqlCon);
                cmd.ExecuteNonQuery();
                cmd.Dispose();

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>  
        /// 删除一条货物信息  
        /// </summary>  
        /// <param name="Cno">货物编号</param>  
        public bool deleteCargoInfo(string Cno)
        {
            try
            {
                string sql = "delete from C where Cno=" + Cno;
                SqlCommand cmd = new SqlCommand(sql, sqlCon);
                cmd.ExecuteNonQuery();
                cmd.Dispose();

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}


Service1.asmx 修改 主要是替换helle world这一部分,增加method

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace WebServiceTest
{
    /// <summary>  
    /// Service1 的摘要说明  
    /// </summary>  
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。  
    // [System.Web.Script.Services.ScriptService]  
    public class Service1 : System.Web.Services.WebService
    {        
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }


#if true
        DBOperation dbOperation = new DBOperation();

        [WebMethod(Description = "获取所有货物的信息")]
        public string[] selectAllCargoInfor()
        {
            return dbOperation.selectAllCargoInfor().ToArray();
        }

        [WebMethod(Description = "增加一条货物信息")]
        public bool insertCargoInfo(string Cname, int Cnum)
        {
            return dbOperation.insertCargoInfo(Cname, Cnum);
        }

        [WebMethod(Description = "删除一条货物信息")]
        public bool deleteCargoInfo(string Cno)
        {
            return dbOperation.deleteCargoInfo(Cno);
        }
#endif
    }
}

以上参考网址:http://blog.csdn.net/zhyl8157121/article/details/8169172


3.建立winform测试界面 

3.1启动vs2010,建立winform,拖动button1按钮。



3.2 添加服务引用》高级》添加web引用》选择URL》添加引用。


点击button按钮,即可查看数据库内容变化,支持表明调用webservice访问sql成功

private void button1_Click(object sender, EventArgs e)
        {
            localhost.Service1 ws = new localhost.Service1();
            string Cname = "monkey";
            int Cnum=2222;
            ws.insertCargoInfo(Cname,Cnum);
            //MessageBox.Show(ws.HelloWorld());

        }



  • 9
    点赞
  • 53
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
以下是C# WinForm中将Excel数据导入到SQL Server数据库中的步骤: 1. 需要添加对Microsoft.Office.Interop.Excel和System.Data.SqlClient的引用。 2. 建立一个Windows Form应用程序,并在表单上添加一个按钮,用于触发导入Excel数据的过程。 3. 在按钮的Click事件中编写代码,打开Excel文件并读取数据。 ```csharp using Excel = Microsoft.Office.Interop.Excel; Excel.Application excelApp = new Excel.Application(); Excel.Workbook workbook = excelApp.Workbooks.Open(@"C:\example.xlsx"); Excel.Worksheet worksheet = workbook.Sheets[1]; int rowsCount = worksheet.UsedRange.Rows.Count; int columnsCount = worksheet.UsedRange.Columns.Count; for (int row = 1; row <= rowsCount; row++) { for (int col = 1; col <= columnsCount; col++) { string cellValue = (worksheet.Cells[row, col] as Excel.Range).Value.ToString(); // Do something with the cell value } } workbook.Close(); excelApp.Quit(); ``` 4. 创建一个SqlConnection对象,用于连接到SQL Server数据库。 ```csharp using System.Data.SqlClient; SqlConnection connection = new SqlConnection("Data Source=serverName;Initial Catalog=databaseName;Integrated Security=True"); connection.Open(); ``` 5. 创建一个SqlCommand对象,用于执行插入语句。 ```csharp SqlCommand command = new SqlCommand("INSERT INTO TableName (Column1, Column2) VALUES (@Value1, @Value2)", connection); command.Parameters.AddWithValue("@Value1", cellValue1); command.Parameters.AddWithValue("@Value2", cellValue2); command.ExecuteNonQuery(); ``` 6. 在循环中使用SqlCommand对象插入数据。 7. 关闭SqlConnection对象。 ```csharp connection.Close(); ``` 完成以上步骤后,您的C# WinForm应用程序就能够将Excel数据导入到SQL Server数据库中了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值