代码改变世界

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

2012-05-25 14:19  Eric.Hu  阅读(17708)  评论(26编辑  收藏  举报

突然接到leader的任务,为运维写个小工具,给一个参数然后调用一个sql脚本文件并替换器内部某个参数,然后执行.

于是工作开始了...

 

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

Microsoft.SqlServer.ConnectionInfo.dll

Microsoft.SqlServer.Smo.dll

--------------------------------------------

using Microsoft.SqlServer.Management.Common;

using Microsoft.SqlServer.Management.Smo;

 

这里有一个小插叙,对于vs2008里可以直接引用这个这两个类库,但在vs2010里的引用就无法找到这两个类库了(不知道微软是怎么考虑的)

还好我电脑vs2008和vs2010都安装了

不过我还是避易就难的讲一下,vs2010在引用里无法找到这两个类库,那我们就想办法找到它,首先我电脑安装了mssqlserver2008 ,

我去X:\Program Files\Microsoft SQL Server\100\SDK\Assemblies 找到

Microsoft.SqlServer.ConnectionInfo.dll

Microsoft.SqlServer.Smo.dll

Microsoft.SqlServer.Management.Sdk.Sfc.dll(这个一定要考到你的程序目录,但你可以不引用)

然后手动添加应用,第三个dll一定要引用,不然会报错

 

下面看代码:

 

 1        //补卡操作
 2         private void PatchCard()
 3         {
 4             string path = System.Environment.CurrentDirectory;
 5             string CardNo = txtCardNo.Text.Trim();
 6             string connectonstring=ConfigurationManager.AppSettings["connectionString"].ToString();
 7             if(CardNo==null||CardNo=="")
 8             {
 9                 MessageBox.Show("卡号不能为空!");
10                 return;
11             }
12             if(!path.EndsWith(@"\"))
13             {
14                 path += @"\";
15             }
16             path+="补蓝鲸卡.sql";    //获取脚本位置
17             if (File.Exists(path))
18             {
19                 FileInfo file = new FileInfo(path);
20                 string script = file.OpenText().ReadToEnd();
21                 script=script.Replace("H00001", CardNo);  //替换脚本里的参数
22                 try
23                 {
                       //执行脚本
24                    SqlConnection conn = new SqlConnection(connectonstring);
25                    Microsoft.SqlServer.Management.Smo.Server server = new Server(new ServerConnection(conn));
26                    int i= server.ConnectionContext.ExecuteNonQuery(script);

27                    if (i == 1)
28                    {
29                        MessageBox.Show("恭喜!\n"+CardNo+" 补卡成功!","成功");
30                        txtCardNo.Text = "";
31                        CreateLog(CardNo, true);
32                    }
33                    else
34                    {
35                        MessageBox.Show("@_@ 再试一次吧!","失败");
36                    }
37                     
38                 }
39                 catch (Exception es)
40                 {
41                     MessageBox.Show(es.Message);
42                     CreateLog(CardNo + "  " + es.Message, false);
43                 }
44             }
45             else
46             {
47                 MessageBox.Show("脚本不存在!");
48                 return;
49             }
50         }

 

OK,搞定了,看是很简单吧~~