我需要从我的c#应用程序运行一个文件中的sql脚本。 问题是它在不同的数据库上创建一个执行命令的对象。C#SQL Server脚本更改数据库问题
在脚本,每次我需要改变它使用的命令
USE [databasename]
,并因为有许多对象创建它使用命令GO
了很多次了当前数据库的时间,所以我读该文件,直到我找到一个GO命令并在数据库中运行该句子;到目前为止这么好,但是在命令运行之后,连接返回到默认数据库(在这种情况下是master),忽略最后一个USE语句。
这是我用来读取文件并执行脚本的代码。
using (StreamReader reader = new StreamReader(databaseScriptFile)) { DatabaseFactory.CreateDatabase() Database db = new SqlDatabase(connectionstring); txbuilder = new StringBuilder(); bool lastExecute = true; while (!reader.EndOfStream) { text = reader.ReadLine(); if (text.Trim().ToUpper() != "GO") { lastExecute = false; txbuilder.AppendLine(text); } else { lastExecute = true; db.ExecuteNonQuery(CommandType.Text, txbuilder.ToString()); txbuilder.Length = 0; } } //Make sure that the last sentence is executed if (!lastExecute) db.ExecuteNonQuery(CommandType.Text, txbuilder.ToString()); }
看来,它会清除各的ExecuteNonQuery命令执行后sp_reset_conection的连接(这是我在探查获得)
是否有acomplish这个任何优雅和简单的方法?
感谢
这与'Enterprise-Library'有什么关系? – 2010-12-03 23:59:43