This guide demonstrates how to execute SQL script files containing multiple statements (potentially spanning several lines) within a C# application. We'll leverage the Microsoft SQL Server Management Objects (SMO) for this task.
Here's a C# code example:
<code class="language-csharp">using System; using Microsoft.SqlServer.Management.Smo; using Microsoft.SqlServer.Management.Common; using System.IO; public class SqlScriptRunner { public void RunScript(string scriptPath, string connectionString) { // Read the entire SQL script from the file. string sqlScript = File.ReadAllText(scriptPath); // Establish a database connection. using (SqlConnection connection = new SqlConnection(connectionString)) { // Create a Server object using the connection. Server server = new Server(new ServerConnection(connection)); // Execute the script using SMO's ExecuteNonQuery. server.ConnectionContext.ExecuteNonQuery(sqlScript); } } }</code>
Implementation Steps:
Microsoft.SqlServer.Management.Smo
and Microsoft.SqlServer.Management.Common
assemblies in your project's references.SqlScriptRunner
and call the RunScript
method, providing the full path to your SQL script file and a valid database connection string.This method offers a clean and efficient way to handle complex SQL scripts within your C# applications. The using
statement ensures proper resource management by automatically closing the database connection.
The above is the detailed content of How Can I Execute an SQL Script File Containing Multiple Statements in C#?. For more information, please follow other related articles on the PHP Chinese website!