In this post we will show you how to run .sql script file in C#. There are two ways to run .sql script file in C# i.e. run a query which is saved in a .sql file or execute a SQL generated script file.
If you want to run a query which is saved in a SQL file in your C# code, you can do it using the below code.
string connectionString = "Your_Connection_String"
FileInfo file = new FileInfo("Your_File_Path");
string script = file.OpenText().ReadToEnd();
SqlConnection con = new SqlConnection(connectionString);
Server server = new Server(new ServerConnection(con));
server.ConnectionContext.ExecuteNonQuery(script);
If you are trying to execute a SQL generated script file you have to remove all "GO". For that you have to use the following code...
string connectionString = "Your_Connection_String"
FileInfo file = new FileInfo("Your_File_Path");
string script = file.OpenText().ReadToEnd();
script = script.Replace("GO","");
SqlConnection con = new SqlConnection(connectionString);
Server server = new Server(new ServerConnection(con));
server.ConnectionContext.ExecuteNonQuery(script);
Please like and share the blog if you find it interesting and helpful.
Related Articles
If you want to run a query which is saved in a SQL file in your C# code, you can do it using the below code.
string connectionString = "Your_Connection_String"
FileInfo file = new FileInfo("Your_File_Path");
string script = file.OpenText().ReadToEnd();
SqlConnection con = new SqlConnection(connectionString);
Server server = new Server(new ServerConnection(con));
server.ConnectionContext.ExecuteNonQuery(script);
If you are trying to execute a SQL generated script file you have to remove all "GO". For that you have to use the following code...
string connectionString = "Your_Connection_String"
FileInfo file = new FileInfo("Your_File_Path");
string script = file.OpenText().ReadToEnd();
script = script.Replace("GO","");
SqlConnection con = new SqlConnection(connectionString);
Server server = new Server(new ServerConnection(con));
server.ConnectionContext.ExecuteNonQuery(script);
Please like and share the blog if you find it interesting and helpful.
Related Articles
- C# Static Classes
- Casting with is and as operators in C#
- Top 10 frequently asked questions on Git
- Null Coalescing operator (??) in C#
- How to improve Asp.Net Application Performance - Part 2
- 10 Interview Questions on Nodejs
- Lock Logoff Restart Shutdown Computer using C#
- String Compare methods in C#
- What is String.Intern?
- Get list of modified objects in Entity Framework : C#
Thanks!
ReplyDelete