在 C# 程序外存储查询的最佳方法

发布于 2024-12-01 11:13:29 字数 199 浏览 3 评论 0原文

我有一些连接字符串和查询需要存储在 C# 程序之外(无法对它们进行硬编码)。现在我正在使用 Visual Studio 的应用程序配置文件。不幸的是,查询需要我的程序中的变量(由用户在运行时选择)才能运行。

我当前的解决方法是将查询分解为配置文件中的各个部分,然后在程序内重新组装它们。我宁愿避免这种情况,因为它使得很难从配置文件中读取查询。有人有更优雅的解决方案吗?

I have some connection strings and queries that I need to store outside my C# program (can't hardcode them). Right now I'm using the application configuration file of 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

花开浅夏 2024-12-08 11:13:29

我更喜欢服务器上接受参数的存储过程。这可以很好地保护您免受 sql 的侵害注入(除非您构造不当),并且是普遍接受的最佳实践。

否则,请使用参数化查询。它们可以存储在配置文件中。 (但如果您继续,我一定要加密.config文件在纯文本配置文件中存储敏感数据(例如连接字符串)和有用的数据(例如可行查询)。)

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.

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

空‖城人不在 2024-12-08 11:13:29

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

A common approach would be using placeholders and replacing them at run time.

注定孤独终老 2024-12-08 11:13:29

如果您必须在程序中包含字符串并且不能使用存储过程,最简单的方法是存储带有已有参数的字符串,如下所示:

select * from Country where city = @ City"

加载此字符串并向您的查询添加参数。始终在生成查询时使用参数。

在您的情况下,这是一种简单、直接、更原生的 SQL 方法 。希望

这有帮助。

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.

Hope this helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文