使用C#在SQL Server上执行sql脚本
SQL Server 2008 R2 Express,.Net Framework 4.0,Visual Studio 2010
我正在尝试从命令提示符应用程序执行SQL脚本。 我找到了一个样本
代码并试图实现相同的。 但是不承认以下使用声明。
using Microsoft.SqlServer.Management.Common; using Microsoft.SqlServer.Management.Smo;
我错过了任何assembly参考吗?
您可能需要SQL Server附带的SDK附带的程序集。 确保在安装SQL Server时安装了SDK 。
(截图取自随机谷歌图片搜索,突出显示的项目是你需要的)
默认情况下,它们位于类似于C:\Program Files (x86)\Microsoft SQL Server\100\SDK\Assemblies
的路径C:\Program Files (x86)\Microsoft SQL Server\100\SDK\Assemblies
版本号可能与您安装的SQL Server版本不同。
以下c#代码使用SMO(SQL Server管理对象)从.sql文件中读取任何sql查询并在SQL Server上执行。
#region Using Directives using System.Configuration; using System.Data.SqlClient; using System.IO; using Microsoft.SqlServer.Management.Common; using Microsoft.SqlServer.Management.Smo; using System.Xml.Linq; using System; #endregion public sealed class DatabaseHandler { #region Properties /// /// Returns the Database Connection String /// public string ConnectionString { get { return ConfigurationManager.AppSettings["DbConnectionString"]; } } #endregion #region Public Methods /// /// Reads the script conent from .sql file and execute on SQl Server /// /// .sql Script file path /// Operation status true: Success false: Failed public bool ExecuteScript(string scriptFilePath) { try { bool isCreated = false; if (!string.IsNullOrWhiteSpace(scriptFilePath)) { FileInfo fileInfo = new FileInfo(scriptFilePath); if (null != fileInfo) { //Holds the sql script as string string scriptText = string.Empty; using (StreamReader reader = fileInfo.OpenText()) { if (null != reader) { scriptText = reader.ReadToEnd(); } } using (SqlConnection connection = new SqlConnection(ConnectionString)) { Server sqlServer = new Server(new ServerConnection(connection)); if (null != sqlServer && null != sqlServer.ConnectionContext) { sqlServer.ConnectionContext.ExecuteNonQuery(scriptText); } } } } isCreated = true; return isCreated; } catch (FileNotFoundException) { throw new FileNotFoundException("Unable to find" + scriptFilePath); } catch (Exception) { throw; } } #endregion }
现在是2017年,有一种更简单的方法。
添加此NuGet包: https : //www.nuget.org/packages/Microsoft.SqlServer.SqlManagementObjects