执行存储为资源的SQL脚本

[英]Executing a SQL script stored as a resource


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).

我想在我的解决方案中存储冗长的.sql脚本并以编程方式执行它们。我已经弄清楚如何执行包含我的sql脚本的字符串,但我还没想出如何从存储在解决方案中的文件中读取字符串(例如,在/ Scripts子文件夹下)。

4 个解决方案

#1


19  

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

首先,编辑.sql文件的属性,以便将其作为资源嵌入。

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();
   }
}

#2


26  

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:

将SQL文件添加到项目中,然后创建新的资源文件。打开SQL文件,从左上角的下拉列表中选择“文件”(默认为字符串)。然后点击添加资源并导航到/选择SQL文件。这允许您从资源文件中获取SQL而不会丢失类型安全性,如下所示:

SqlFiles.SqlScript

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

以上是Visual Studio 2010中的过程。我也在我的博客上写过这个。

#3


0  

Add file to Resources, and set file to Resource, in code write:

将文件添加到Resources,并在代码写入中将文件设置为Resource:

String SQLCommand = NAMESPACE.Properties.Resources.ScriptDB.ToString()

#4


0  

Use QueryFirst. You put your sql in .sql template provided by the tool. Behind the scenes, QueryFirst compiles it as a resource and wires up the call to retrieve it at runtime. You only need to worry about calling Execute() on the generated wrapper class, and your results are accessible via generated POCOs. End to end type safety. Never have to remember a column name or datatype, plus the considerable advantages of having your sql where god intended... in a .sql file.

使用QueryFirst。您将sql放在该工具提供的.sql模板中。在幕后,QueryFirst将其编译为资源并连接调用以在运行时检索它。您只需要担心在生成的包装类上调用Execute(),并且可以通过生成的POCO访问结果。端到端类型安全。永远不必记住列名或数据类型,以及在.sql文件中使用sql所希望的sql的相当大的优势。

disclaimer: I wrote QueryFirst

免责声明:我写了QueryFirst

关注微信公众号

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2009/09/04/6c4e8ff098843a4dc42c713676073bce.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com