简体   繁体   English

在C#中存储程序过时查询的最佳方法

[英]Best way to store queries outisde of program in C#

I have some connection strings and queries that I need to store outside my C# program (can't hardcode them). 我有一些存储在C#程序外部的连接字符串和查询(无法对其进行硬编码)。 Right now I'm using the application configuration file of Visual Studio. 现在,我正在使用Visual Studio的应用程序配置文件。 Unfortunately the queries require variables (chosen at run-time by the user) from my program to run. 不幸的是,查询需要我的程序中的变量(由用户在运行时选择)才能运行。

My current workaround is to break up the query into pieces in the configuration file and reassemble them inside the program. 我当前的解决方法是将查询分解为配置文件,然后在程序中重新组合它们。 I'd prefer to avoid this, since it makes it hard to read the query from the configuration file. 我宁愿避免这种情况,因为这样会使从配置文件中读取查询变得困难。 Does anyone have a more elegant solution? 有谁有一个更优雅的解决方案?

Stored procedures on the server that accept the parameters would be my preference. 我希望使用服务器上接受参数的存储过程 That protects you fairly well from sql injection (unless you construct them improperly), and is the commonly accepted best practice. 这样可以很好地保护您免受sql注入的侵害 (除非您不正确地构造它们),并且这是公认的最佳实践。

Otherwise, use parameterized queries. 否则,请使用参数化查询。 They can be stored in the config file. 它们可以存储在配置文件中。 (But I'd be darn sure to encrypt the .config file if you continue to store sensitive data like connection strings and helpful things like workable queries in a plain-text config file.) (但是,如果您继续在纯文本配置文件中存储敏感数据(如连接字符串)和有用的信息(如可行的查询),那么我将确保对.config文件进行加密 。)

一种常见的方法是使用占位符并在运行时替换它们。

If you must have strings out of your program and can not use Stored Procedures, the easiest way would be to store string with already paramaters, something like this: 如果您的程序中必须有字符串并且不能使用存储过程,则最简单的方法是使用已经具有参数的字符串存储字符串,如下所示:

select * from Country where city = @City" 从城市= @城市的国家中选择*”

Load this string and add a parameter to your query. 加载此字符串并将参数添加到您的查询。 Always use parameters on query generation. 始终在生成查询时使用参数。

This is simple, straightforward and more SQL native approach that come in my mind now in your case. 现在,在您的情况下,我想到了这种简单,直接和更多的SQL本机方法。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM