这是一个人为的例子,但为了便于解释,我对其进行了简化。
Please see my update at the bottom before investing too much of your time!
背景
我有一些(很多)代码通常按如下方式查询我的数据库:
SELECT name FROM sites where IsLive=1;
我的挑战是,在特定条件下,返回网站的完整列表,本质上
SELECT name from sites;
我不想修改发出 SQL 的实际 C# 代码(尽管我可以这样做,以实现我的目标,这纯粹是为了演示目的)。
因此,为了尽可能保持原状,我的想法是插入一个名为 site 的 database-proxy-view
,它根据 control variable< 返回数据
方法
- 将现有的
site
表重命名为site_table
- 创建一个名为
site
的新 View ,C# 代码现在在不知不觉中将其作为目标,并返回site_table
中的(可能已过滤的)详细信息control variable
值(注意 View 中变量的限制意味着我必须创建一个函数来演示这一点 - 参见 http://dev.mysql.com/doc/refman/5.7/en/create-view.html wrt error 1351)
所做的更改
ALTER TABLE 站点重命名为 site_table;
创建函数 controlVariableFn() RETURNS VARCHAR(16) RETURN @controlVariable;
CREATE OR REPLACE VIEW site AS SELECT * from site_table WHERE (IsLive = 1 OR controlVariableFn() = 'SHOWALL');
上面的语句是丑陋的,但实现了我想要的结果,但是我的问题是动态传递 controlVariable
而不改变我发送的主要 SQL 查询。
我的问题
有没有办法(理想情况下,当我创建我的连接对象时)在要执行的实际 SQL 之外定义 controlVariable
但 View 仍然可以访问类似的就好像它已作为常规用户变量参数提供给查询一样?
所以代码看起来像
var connectionString = "Server=localhost;User ID=un;Password=pw;Database=dbname;....";
DbConnection db = new MySql.Data.MySqlClient.MySqlConnection
(connectionString, "controlVariable=SHOWALL");
var results = db.Query<Site>("SELECT * FROM site;");
(我知道这不是一个明智的永久解决方案)
Update My preferred solution as outlined above will not work for me as once I get into my data access layer as the results set will essentially be filtered again back to the original set. There are some circumstances where it could work; it would depend on the SQL issued (e.g. when collapsing a results set down instead of trying to expand a results set as I was trying to do here). In that regard I am no longer looking for an answer here but will leave it for posterity as a preferred option and as per the guidelines - thanks anyway.
最佳答案
如果您不想编辑 C# 代码,则必须将变量存储在数据库中,但我不确定您将如何不编辑代码。 如果您愿意编辑代码,那么您可以访问辅助配置表,该表将包含您希望用户传递给 View 的设置。接受它并允许用户选择他们想要的,然后通过应用程序将其传递给 View 。
关于c# - 通过连接字符串或连接对象设置 MySQL 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37487443/