WPF数据库编程,存储过程查询以及增删改。

1.目的和功能以及效果截图

  目的:复习存储过程; 

        学会在.NET平台里操作存储过程。

  

  功能:无参数的存储过程的查询;

        带一个输入参数的存储过程的查询;

        带一个输入参数一个输出参数的存储过程的查询;(存储过程的查询功能)

        增加信息到数据库的存储过程、

        删除信息到数据库的存储过程。

        更新信息到数据库的存储过程。

  效果截图:

 

2.基本步骤

 

 

    建立数据库SuperMarket(创建表,设置表之间的主外键关系,添加数据)---写存储过程  (数据库部分)

   新建一个WPF工程WPFAdoProc----添加一个接口Proc.cs(查询,增删改的主要功能实现部分)---MainWindow.xaml前台

-----MainWindow.xaml.cs后台部分  (.net部分)

3.实现代码及思路讲解

(数据库部分)基本代码:

use master;
go
create database SuperMarket
on primary
(name="SuperMarket",
filename="C:SuperMarket.mdf",
size=4MB, filegrowth=1MB)
LOG ON
(name="SuperMarket_log",
filename="C:SuperMarket_log.mdf",
size=2MB, maxsize=20MB,filegrowth=10%)
collate Chinese_PRC_CI_AS;
go
use SuperMarket;
go
/*==============================================================*/
/* Table: 岗位信息                                                 */
/*==============================================================*/
create table 岗位信息 (
   岗位ID          char(6)   primary key,
   岗位名称        nvarchar(20)   
)
go
/*==============================================================*/
/* Table: 员工信息                                                 */
/*==============================================================*/
create table 员工信息 (
   员工ID          char(6)   primary key,
   员工姓名        nvarchar(20)   
)
go
/*==============================================================*/
/* Table: 员工岗位信息                                                 */
/*==============================================================*/
create table 员工岗位信息 (
   ID        int identity(1,1) primary key,
   员工ID          char(6)   
   constraint fk_员工岗位信息_员工ID
    foreign key references 员工信息(员工ID),
   岗位ID          char(6)   
   constraint fk_员工岗位信息_岗位ID
    foreign key references 岗位信息(岗位ID)
)
go
/*==============================================================*/
/* Table: 供应商信息                                            */
/*==============================================================*/
create table 供应商信息 (
   供应商ID          char(6)   primary key,
   供应商名称        nvarchar(20)          
)
go
/*==============================================================*/
/* Table: 客户信息                                            */
/*==============================================================*/
create table 客户信息 (
   客户ID          char(6)   primary key,
   客户名称        nvarchar(20)     null
)
go
/*==============================================================*/
/* Table: 部门信息                                              */
/*==============================================================*/
create table 部门信息 (
   部门ID          char(6)   primary key,
   部门名称        nvarchar(20)          
)
go
/*==============================================================*/
/* Table: 部门员工信息                                                 */
/*==============================================================*/
create table 部门员工信息 (
   ID        int identity(1,1) primary key,
   员工ID          char(6)   
   constraint fk_部门员工信息_员工ID
    foreign key references 员工信息(员工ID),
   部门ID          char(6)   
   constraint fk_部门员工信息_部门ID
    foreign key references 部门信息(部门ID)
)
go
/*==============================================================*/
/* Table: 商品信息                                            */
/*==============================================================*/
create table 商品信息 (
   商品ID          char(13) primary key,     /*EAN-13条码:13位*/   
   制造商ID        char(6) 
    constraint fk_商品信息_供应商ID
    foreign key references 供应商信息(供应商ID),
   商品名称        nvarchar(20)  ,
   计量单位        nchar(6)        
)
go
/*==============================================================*/
/* Table: 仓库信息                                              */
/*==============================================================*/
create table 仓库信息 (
   仓库ID          char(6)   primary key,
   仓库名称        nvarchar(20)          ,
   仓库地址        text   
)
go
/*==============================================================*/
/* Table: 库存信息                                              */
/*==============================================================*/
create table 库存信息 (
   商品ID          char(13)   primary key,/*商品ID中包含了商品信息、生产厂家、生产时间以及有效期信息,同意名称的商品将有可能采用不同的商品ID*/
   仓库ID          char(6)              
   constraint fk_库存信息_仓库ID
    foreign key references 仓库信息(仓库ID),
   入库均价        decimal(12,2)          null,/* 库存信息中的入库均价,需要对多次入库时商品的价格进行平均,并且需要考虑计量单位和计量因子*/ 
   当前数量        decimal(12,2)          ,/* 库存信息中的当前数量针对的计量单位只能按《商品信息》表中的计量单位执行 (计量因子=1)*/ 
   constraint fk_库存信息_商品ID
       foreign key(商品ID) references 商品信息(商品ID)
)
go


/*==============================================================*/
/* Table: 采购信息                                              */
/*==============================================================*/
create table 采购信息 (
   采购单ID        char(12)  primary key,
   采购日期        datetime          ,
   采购部门ID      char(6)           
   constraint fk_采购信息_采购部门ID
    foreign key references 部门信息(部门ID),
   采购员ID        char(6)           
   constraint fk_采购信息_采购员ID
    foreign key references 员工信息(员工ID),
   供应商ID        char(6) null 
    constraint fk_采购信息_供应商ID
    foreign key references 供应商信息(供应商ID),
)
go
/*==============================================================*/
/* Table: 采购明细                                              */
/*==============================================================*/
create table 采购明细 (
   采购明细ID      UNIQUEIDENTIFIER  default(newid())  primary key,
   采购单ID        char(12)          
    constraint fk_采购明细_采购单ID
    foreign key references 采购信息(采购单ID),
   商品ID          char(13)           
     constraint fk_采购明细_商品ID
       foreign key references 商品信息(商品ID),
   计量单位        nchar(6)          ,  /* 采购时的计量单位可以根据实际情况输入 */   
   计量因子        decimal(12,2)     , /* 计量因子是采购时的计量单位与《商品信息》表中该商品计量单位的比值 */  
   采购数量        decimal(12,2)     , /* 按采购计量单位计算数量 */
   采购单价        decimal(12,2)      /* 按采购计量单位计算数量 */                  
)

/*==============================================================*/
/* Table: 入库信息                                              */
/*==============================================================*/
create table 入库信息 (
   入库单ID        char(12)  primary key,
   入库日期        datetime          ,
   库管员ID        char(6)           
   constraint fk_入库信息_库管员ID
    foreign key references 员工信息(员工ID),
   入库部门ID      char(6)           ,   /*内部入库,如生产部等(产品,半成品)  */ 
   部门代表ID        char(6)           
   constraint fk_入库信息_部门代表ID
    foreign key references 员工信息(员工ID),
   采购单ID        char(12)      null    /*采购入库,如采购部等  */
   constraint fk_入库信息_采购单ID
    foreign key references 采购信息(采购单ID),  
   备注            text          null    /* 说明入库事由  */
)
go
/*==============================================================*/
/* Table: 入库明细                                              */
/*==============================================================*/
create table 入库明细 (
   入库明细ID      UNIQUEIDENTIFIER  default(newid())  primary key,
   入库单ID        char(12)          
   constraint fk_入库明细_入库单ID
    foreign key references 入库信息(入库单ID),
   商品ID          char(13)           
   constraint fk_入库明细_商品ID
    foreign key references 商品信息(商品ID),
   入库数量        decimal(12,2)           ,
   入库单价        decimal(12,2)       null
)
go
/*==============================================================*/
/* Table: 销售信息                                              */
/*==============================================================*/
create table 销售信息 (
   销售单ID        char(12)  primary key,
   销售日期        datetime          ,
   销售部门ID      char(6)           
   constraint fk_销售信息_部门ID
    foreign key references 部门信息(部门ID),
   客户ID          char(6) 
   constraint fk_销售信息_客户ID
    foreign key references 客户信息(客户ID)         
)
go
/*==============================================================*/
/* Table: 销售明细                                              */
/*==============================================================*/
create table 销售明细 (
   销售明细ID      UNIQUEIDENTIFIER  default(newid())  primary key,
   销售单ID        char(12)
    constraint fk_销售明细_销售单ID
    foreign key references 销售信息(销售单ID),
   商品ID          char(13)           
   constraint fk_销售明细_商品ID
    foreign key references 商品信息(商品ID),
   销售数量        decimal(12,2)           , 
   销售单价        decimal(12,2)                   
)
/*==============================================================*/
/* Table: 出库信息                                              */
/*==============================================================*/
create table 出库信息 (
   出库单ID        char(12)  primary key,   
   仓库ID          char(6),
   出库日期        datetime          ,
   出库部门ID      char(6)       null/*内部领用或调拨出库,如生产部等(半成品)  */
   constraint fk_出库信息_部门ID
    foreign key references 部门信息(部门ID),
   销售单ID        char(12)       null/*销售出库,如销售部等  */
   constraint fk_出库信息_销售单ID
    foreign key references 销售信息(销售单ID),
   备注            text          null/* 说明出库事由  */
)
go
/*==============================================================*/
/* Table: 出库明细                                              */
/*==============================================================*/
create table 出库明细 (
   出库明细ID      UNIQUEIDENTIFIER  default(newid())  primary key,
   出库单ID        char(12)          
    constraint fk_出库明细_出库单ID
    foreign key references 出库信息(出库单ID),
   商品ID          char(13)       
   constraint fk_出库明细_商品ID
    foreign key references 商品信息(商品ID),
   出库数量        decimal(12,2)       ,  
   出库单价        decimal(12,2)    null  
)
go
/*==============================================================*/
/* Type: 采购明细临时表                                              */
/*==============================================================*/
create type 采购明细临时表 as Table  
(  
   商品ID          char(13)           ,
   计量单位        nchar(6)          ,  /* 采购时的计量单位可以根据实际情况输入 */   
   计量因子        decimal(12,2)     , /* 计量因子是采购时的计量单位与《商品信息》表中该商品计量单位的比值 */  
   采购数量        decimal(12,2)     , /* 按采购计量单位计算数量 */
   采购单价        decimal(12,2)      /* 按采购计量单位计算数量 */
)  
/*==============================================================*/
/* Type: 入库明细临时表                                              */
/*==============================================================*/
create type 入库明细临时表 as Table  
(  
   商品ID          char(13)                ,
   入库数量        decimal(12,2)           ,/* 入库时的计量单位《商品信息》表中该商品计量单位计算,计量因子=1 入库单价*/
   入库单价        decimal(12,2)       null/* 入库单价按《商品信息》中该商品计量单位对应的入库价格计算 */
)  
Go
/*==============================================================*/
/* Type: 出库明细临时表                                              */
/*==============================================================*/
create type 出库明细临时表 as Table  
(  
   商品ID          char(13)            , 
   出库数量        decimal(12,2)       ,  /* 出库数量的计量单位按《商品信息》表中的计量单位计算 */ 
   出库单价        decimal(12,2)    null  /* 出库单价按《商品信息》表中的计量单位,以及出库时该商品的库存均价计算 */
)  
Go
/*==============================================================*/
/* Type: 销售明细临时表                                              */
/*==============================================================*/
create type 销售明细临时表 as Table  
(  
   商品ID          char(13)            ,  
   销售数量        decimal(12,2)       ,  /* 销售数量的计量单位按《商品信息》表中的计量单位计算 */ 
   销售单价        decimal(12,2)    null  /* 销售单价按《商品信息》表中的计量单位的销售单价计算 */
)  
Go

     
View Code

存储过程代码:

use SuperMarket;
go
create proc 查询全体岗位信息
as
  select 岗位ID,岗位名称 from 岗位信息
go



exec 查询全体岗位信息
go

-----------------1


use SuperMarket;
go
create proc 查询岗位信息ByID
@岗位ID char(6)
as
  select 岗位ID,岗位名称 from 岗位信息
    where 岗位ID=@岗位ID
go




use SuperMarket;
go
exec 查询岗位信息ByID 'W4'
go
---------------------2

use SuperMarket;
go
create proc 根据部门ID查询员工信息并取得员工数量
@部门ID char(6),
@员工数目 int out
as
begin
    select @员工数目=COUNT(*)
    from 部门员工信息
    where 部门ID=@部门ID;
    select  A.员工姓名,B.部门名称  from 部门员工信息 as C
      inner join 员工信息 as A
       on C.员工ID=A.员工ID
      inner join 部门信息 as B
       on C.部门ID=B.部门ID
      where C.部门ID=@部门ID;
end
go




use SuperMarket;
go
declare @员工数目 as int;
exec 根据部门ID查询员工信息并取得员工数量 'D00', @员工数目;
go
--------内连接查询

use SuperMarket;
go
create proc 增加部门信息
@部门ID char(6),
@部门名称 nvarchar(20)
as
begin
    DECLARE  @errorSum int;
    set @errorSum=0;
    begin transaction 
        insert into 部门信息 values(@部门ID,@部门名称);
    if @errorSum<>0
      rollback transaction;
    else
      commit transaction;
end
go

------插入

use SuperMarket;
go
create proc 删除部门信息
@部门ID char(6)
as
begin
    DECLARE  @errorSum int;
    set @errorSum=0;
    begin transaction 
        delete from 部门信息 where 部门ID=@部门ID;
    if @errorSum<>0
    rollback transaction;
  else
    commit transaction;
end
go
----删除


create proc 更新部门信息
@部门ID char(6),
@部门名称 nvarchar(20)
as
begin
    DECLARE  @errorSum int;
    set @errorSum=0;
    begin transaction 
        update 部门信息  set 部门名称=@部门名称 where 部门ID=@部门ID;
    if @errorSum<>0
    rollback transaction;
  else
    commit transaction;
end
go
----更新
View Code

(WPF部分)

 接口Proc.cs代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace WpfAdoProc
{
    public interface Proc
    {

        DataSet get查询全体岗位信息();
        DataSet 查询岗位信息ByID(string 岗位ID);
        DataSet 根据部门ID查询员工信息并取得员工数量(string 部门ID, out int 员工数目);


        void 增加部门信息(string 部门ID, string 部门名称);
        void 删除部门信息(string 部门ID);
        void 更新部门信息(string 部门ID, string 部门名称);
    }


    public class TestDataSet1 : Proc
    {
        private SqlConnection conn;
        public TestDataSet1()
        {

            string str = @"Data Source=.SQLEXPRESS2008;Integrated Security=SSPI;database=SuperMarket;";
            conn = new SqlConnection(str);

        }//构造函数SQL的连接字符串



        public DataSet get查询全体岗位信息()
        {
            DataSet ds = new DataSet();
            if (conn == null) return null;//
            SqlCommand cmd = new SqlCommand("查询全体岗位信息", conn);



            cmd.CommandType = CommandType.StoredProcedure;//指定解释存储过程的解释语句。存储过程无参数的使用代码。



            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds, "岗位信息");
            return ds;


        }


        public DataSet 查询岗位信息ByID(string 岗位ID)
        {

            DataSet ds = new DataSet();
            if (conn == null) return null;
            SqlCommand cmd = new SqlCommand("查询岗位信息ByID", conn);




            cmd.Parameters.Add(new SqlParameter("@岗位ID", SqlDbType.Char, 6)).Value = 岗位ID;
            cmd.CommandType = CommandType.StoredProcedure;//存储过程带参数的使用的代码



            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds, "岗位信息");
            return ds;


        }



        public DataSet 根据部门ID查询员工信息并取得员工数量(string 部门ID, out int 员工数目)
        {
            DataSet ds = new DataSet();
            员工数目 = 0;

            if (conn == null) return null;

            SqlCommand cmd = new SqlCommand("根据部门ID查询员工信息并取得员工数量", conn);//要和数据库里面的存储过程名字一样

            cmd.CommandType = CommandType.StoredProcedure;//指明是存储过程
            cmd.Parameters.Add(new SqlParameter("@部门ID", SqlDbType.Char, 6)).Value = 部门ID;//输入参数
            cmd.Parameters.Add(new SqlParameter("@员工数目", SqlDbType.Int)).Direction = ParameterDirection.Output;//输出参数

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds, "部门员工信息");
            员工数目 = ((int)cmd.Parameters["@员工数目"].Value);//因为是int类型,所以要转换,要设置初始值

            return ds;


        }


        public void 增加部门信息(string 部门ID, string 部门名称)
        {
            DataSet ds = new DataSet();
            if (conn == null) return;


            SqlCommand cmd = new SqlCommand("增加部门信息", conn);
            cmd.Parameters.Add(new SqlParameter("@部门ID", SqlDbType.Char, 6)).Value = 部门ID; //输入参数
            cmd.Parameters.Add(new SqlParameter("@部门名称", SqlDbType.NChar, 20)).Value = 部门名称; //输入参数
            cmd.CommandType = CommandType.StoredProcedure;

            if (conn.State == ConnectionState.Closed)
                conn.Open();
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex) { }
        }

        public void 删除部门信息(string 部门ID)
        {
            DataSet ds = new DataSet();
            if (conn == null) return;
            SqlCommand cmd = new SqlCommand("删除部门信息", conn);
            cmd.Parameters.Add(new SqlParameter("@部门ID", SqlDbType.Char, 6)).Value = 部门ID; //输入参数
            cmd.CommandType = CommandType.StoredProcedure;

            if (conn.State == ConnectionState.Closed)
                conn.Open();
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex) { }
        }


        public void 更新部门信息(string 部门ID, string 部门名称)
        {
            DataSet ds = new DataSet();
            if (conn == null) return;


            SqlCommand cmd = new SqlCommand("更新部门信息", conn);
            cmd.Parameters.Add(new SqlParameter("@部门ID", SqlDbType.Char, 6)).Value = 部门ID; //输入参数
            cmd.Parameters.Add(new SqlParameter("@部门名称", SqlDbType.NChar, 20)).Value = 部门名称; //输入参数
            cmd.CommandType = CommandType.StoredProcedure;


            if (conn.State == ConnectionState.Closed)
                conn.Open();
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex) { }
        }
    }

}
View Code

前台MainWindow.xaml部分

<Window x:Class="WpfAdoProc.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="416" Width="701">
    <Grid>
        <Button Content="无参数存储过程查询全体员工" Height="23" HorizontalAlignment="Left" Margin="23,22,0,0" Name="button1" VerticalAlignment="Top" Width="184" Click="button1_Click" />
        <RichTextBox Height="337" HorizontalAlignment="Left" Margin="267,12,0,0" Name="richTextBox1" VerticalAlignment="Top" Width="259" />
        <Button Content="有输入参数的存储过程" Height="23" HorizontalAlignment="Left" Margin="23,80,0,0" Name="button2" VerticalAlignment="Top" Width="184" Click="button2_Click_1" />
        <Button Content="有输入输出参数的存储过程" Height="23" HorizontalAlignment="Left" Margin="23,157,0,0" Name="button3" VerticalAlignment="Top" Width="184" Click="button3_Click_1" />
        <Button Content="增加部门信息" Height="23" HorizontalAlignment="Left" Margin="84,214,0,0" Name="button4" VerticalAlignment="Top" Width="107" Click="button4_Click" />
        <Button Content="删除部门信息" Height="23" HorizontalAlignment="Left" Margin="84,265,0,0" Name="button5" VerticalAlignment="Top" Width="107" Click="button5_Click" />
        <Button Content="更新部门信息" Height="23" HorizontalAlignment="Left" Margin="84,317,0,0" Name="button6" VerticalAlignment="Top" Width="107" Click="button6_Click" />
    </Grid>
</Window>
View Code

后台MainWindow.xaml.cs部分

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;

namespace WpfAdoProc
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {

        Proc pc;
        public MainWindow()
        {
            InitializeComponent();
            pc = new TestDataSet1();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            richTextBox1.Document.Blocks.Clear();
            foreach (DataRow t in pc.get查询全体岗位信息().Tables["岗位信息"].AsEnumerable()) //用DataRow取出接口实现方法,从而使用存储过程。                                     
            {

                richTextBox1.AppendText("岗位ID=" + t["岗位ID"].ToString());//"员工ID="是要显示的信息,可以随便改   t["员工ID"].ToString()是数据库的员工ID

                richTextBox1.AppendText("岗位名称=" + t["岗位名称"].ToString() + "
");



            }
        }

        private void button2_Click_1(object sender, RoutedEventArgs e)
        {
            richTextBox1.Document.Blocks.Clear();

            foreach (DataRow t in pc.查询岗位信息ByID("W4").Tables["岗位信息"].AsEnumerable())
            {

                richTextBox1.AppendText("岗位ID=" + t["岗位ID"].ToString());//"员工ID="是要显示的信息,可以随便改   t["员工ID"].ToString()是数据库的员工ID

                richTextBox1.AppendText("岗位名称=" + t["岗位名称"].ToString() + "
");

            }

        }

        private void button3_Click_1(object sender, RoutedEventArgs e)
        {
            int 员工数目 = 0;
            foreach (DataRow t in pc.根据部门ID查询员工信息并取得员工数量("D00", out 员工数目).Tables["部门员工信息"].AsEnumerable())
            {
                richTextBox1.AppendText("员工姓名=" + t["员工姓名"].ToString() + "
");
                richTextBox1.AppendText("部门名称=" + t["部门名称"].ToString() + "
");


            }

            richTextBox1.AppendText("员工数目=" + 员工数目.ToString() + "
");
        }

        private void button4_Click(object sender, RoutedEventArgs e)
        {
            pc.增加部门信息("D06", "生产部");//可以加个MessageBox消息框
   
        }

        private void button5_Click(object sender, RoutedEventArgs e)
        {
            pc.删除部门信息("D06");
   
        }

        private void button6_Click(object sender, RoutedEventArgs e)
        {
            pc.更新部门信息("D06", "营销部");
            

       
        }

       


    }
}
View Code

注意:在连接字符串要配置  string str = @"Data Source=PC01;Integrated Security=SSPI;database=SuperMarket";  其中Data Source=xxx(你的SqlServer的实例登录名,这里我的是用的计算机名称PC01)  实例登录名即你登录SQLSERVER选择的登陆名,大多数可能会是计算机名字,或者默认的实例名是计算机名字/SQLEXPRESS。

原文地址:https://www.cnblogs.com/Energy240/p/3622043.html