C# 执行作为资源存储的 SQL 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1379195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Executing a SQL script stored as a resource
提问by Yann Semet
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 子文件夹下)。
采纳答案by Av Pinzur
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();
}
}
回答by Daniel Imms
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,而不会丢失您的类型安全性,如下所示:
The above is the process in Visual Studio 2010. I also wrote about this on my blog.
以上是Visual Studio 2010中的流程,我的博客也写过这个。
回答by Darlan Dieterich
Add file to Resources, and set file to Resource, in code write:
将文件添加到Resources,并将文件设置为Resource,在代码中编写:
String SQLCommand = NAMESPACE.Properties.Resources.ScriptDB.ToString()
回答by bbsimonbb
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 文件中。
disclaimer: I wrote QueryFirst
免责声明:我写了 QueryFirst