统计 |
blog名称:人在旅途 日志总数:175 评论数量:505 留言数量:13 访问次数:1658010 建立时间:2005年12月7日 |
生命是过客,人在旅途。奶奶是信基督教的,没啥文化,却养育了四子二女,还带过九个孙辈。老人家对生命的看法就是“人都是客人,迟早要回去的。”就以《人在旅途》来纪念她。

« | July 2025 | » | 日 | 一 | 二 | 三 | 四 | 五 | 六 | | | 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 | | | |
|
公告 |
本人上传的源程序中可能引用或使用了第三方的库或程序,也可能是修改了第三方的例程甚至是源程序.所以本人上传的源程序禁止在以单纯学习为目的的任何以外场合使用,不然如果引起任何版权问题,本人不负任何责任. | |

|
本站首页 管理页面 写新日志 退出
调整中...
[微软技术开发]如何用C#编写能运行SQL Script的程序 |
人在旅途 发表于 2008/4/11 10:56:44 | 一下转自http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1878660&SiteID=1
You can't run files directly, with just specifing file name. You must first read it's content in a string and then execute CommandText command. But this will work as long you don't have GO statement in your sql script. From your post it looks like that SqlCommand is not usefull because scripts that include DDL command are completed with batch finalizer GO command. Luckily, since SQL Server 2005, you can use smo library to do this operation and not use batch command and osql connection as previously. Here is how to do it:
using System.Data.SqlClient;
using System.IO;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string sqlConnectionString = "Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True";
FileInfo file = new FileInfo("C:\\myscript.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
}
}
}
The files you need to reference are:
Microsoft.SqlServer.ConnectionInfo
Microsoft.SqlServer.Smo
Took me a few minutes to find at first. If you can't find them in the .NET tab, you might not have it installed. The paths on my computer to these files are:
c:\Program Files\Microsoft SQL Server\90\SDK\Assemblies\Microsoft.SqlServer.ConnectionInfo.dll
c:\Program Files\Microsoft SQL Server\90\SDK\Assemblies\Microsoft.SqlServer.Smo.dll
如果找不到以上文件,可从http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=d09c1d60-a13c-4479-9b91-9e8b9d835cdc下载<Microsoft SQL Server 2005 Management Objects Collection>并安装后在寻找.
|
阅读全文(4333) | 回复(1) | 编辑 | 精华 |
回复:如何用C#编写能运行SQL Script的程序 |
真不准发表评论于2008/4/11 20:30:40 | 与其这样处理文件我宁可写SP了。
以下为blog主人的回复:
各种方法都有它的用处,SP是专业人员用的.我的程序就建立在SP的基础上,所有数据库使用前要初始化,生成TABLE和很多SP.但不能让用户自己去运行我提供的SCRIPT文件来生成TABLE和SP,应该让用户能在应用程序中自己选择数据库,然后按一个按钮而自动运行SCRIPT文件.所以本贴的方法就有用了.
老兄大概是搞研究工作的吧,我一直做应用的.
|
个人主页 | 引用回复 | 主人回复 | 返回 | 编辑 | 删除 | » 1 »
|