Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing a SQL script stored as a resource

Tags:

I would like to store lengthy .sql scripts in my solution and execute them programmatically. I've already figured out how to execute a string containing my sql script but I haven't figured out how to read the string from a file that would be stored in the solution (under a /Scripts subfolder for example).

like image 255
Yann Semet Avatar asked Sep 04 '09 13:09

Yann Semet


2 Answers

Add the SQL files to your project then create a new resource file. Open up the SQL file and select 'Files' from the top-left drop down (default is Strings). Then hit add resource and navigate to/select the SQL file. This allows you to get SQL from the resource file without losing your type-safety like so:

SqlFiles.SqlScript

The above is the process in Visual Studio 2010. I also wrote about this on my blog.

like image 140
Daniel Imms Avatar answered Oct 14 '22 00:10

Daniel Imms


First, edit the .sql file's properties so that it will be embedded as a resource.

Then use code similar to the following to retrieve the script:

string commandText;
Assembly thisAssembly = Assembly.GetExecutingAssembly();
using (Stream s = thisAssembly.GetManifestResourceStream(
      "{project default namespace}.{path in project}.{filename}.sql"))
{
   using (StreamReader sr = new StreamReader(s))
   {
      commandText = sr.ReadToEnd();
   }
}
like image 45
Av Pinzur Avatar answered Oct 13 '22 23:10

Av Pinzur