執行存儲為資源的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