C# 调用并执行SQL脚本文件

44 篇文章 0 订阅

让C#程序直接执行sql脚本文件,类似SSMS直接打开sql文件并执行一样,搜索了一下结果还真有,不过需要借用mssql的几个类库及命名空间:

Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Smo.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
添加上面三个dll的引用

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
  //补卡操作
          private  void PatchCard ( )
          {
              string path  =  System . Environment . CurrentDirectory ;
              string CardNo  = txtCardNo . Text . Trim ( ) ;
              string connectonstring =ConfigurationManager . AppSettings [ "connectionString" ] . ToString ( ) ;
              if (CardNo == null ||CardNo == "" )
              {
                 MessageBox . Show ( "卡号不能为空!" ) ;
                  return ;
              }
              if ( !path . EndsWith ( @"\" ) )
              {
                 path  +=  @"\" ;
              }
             path += "补蓝鲸卡.sql" ;     //获取脚本位置
              if  (File . Exists (path ) )
              {
                 FileInfo file  =  new FileInfo (path ) ;
                  string script  = file . OpenText ( ) . ReadToEnd ( ) ;
                 script =script . Replace ( "H00001", CardNo ) ;   //替换脚本里的参数
                  try
                  {
                        //执行脚本
                    SqlConnection conn  =  new SqlConnection (connectonstring ) ;
                    Microsoft . SqlServer . Management . Smo . Server server  =  new Server ( newServerConnection (conn ) ) ;
                     int i = server . ConnectionContext . ExecuteNonQuery (script ) ;
                     if  (==  1 )
                     {
                        MessageBox . Show ( "恭喜!\n" +CardNo + " 补卡成功!", "成功" ) ;
                        txtCardNo . Text  =  "" ;
                        CreateLog (CardNo,  true ) ;
                     }
                     else
                     {
                        MessageBox . Show ( "@_@ 再试一次吧!", "失败" ) ;
                     }
                     
                  }
                  catch  (Exception es )
                  {
                     MessageBox . Show (es . Message ) ;
                     CreateLog (CardNo  +  "  "  + es . Messagefalse ) ;
                  }
              }
              else
              {
                 MessageBox . Show ( "脚本不存在!" ) ;
                  return ;
              }
          }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值