简体   繁体   English

MySQL查询替换字符串

[英]Mysql Query Replacement String

I am trying to take a value from my GUI and use it in my query. 我试图从GUI中获取一个值,并在查询中使用它。 How can I go about this using C#? 我该如何使用C#进行此操作? I am trying to use the GUI value to replace the 'cid'. 我正在尝试使用GUI值替换“ cid”。

 string query = "SELECT firstname, lastname, quanitybought FROM customers s, beersbought a WHERE exists(SELECT 'x' FROM beersbought b WHERE b.cid = s.cid)";

Is there a way to replace the cids with the value I receive from my GUI? 有没有办法用我从GUI收到的值替换cid? For example Where b.GUIVALUE = s.GUIVALUE. 例如,其中b.GUIVALUE = s.GUIVALUE。

Have a look at String.Format() as you can easily achieve what you want using something like 看一下String.Format(),因为您可以使用类似的东西轻松实现所需的内容

string query = string.Format("SELECT firstname, lastname, quanitybought FROM customers s, beersbought a WHERE exists(SELECT 'x' FROM beersbought b WHERE {0} = {1})", bCidUIControl.Text, sCidUIControl.Text);

The above assumes that you have 2 UI Controls (named bCidUIControl and sCidUIControl) such as a TextBox where the parameter values are set/selected. 上面的示例假设您有2个UI控件(分别名为bCidUIControl和sCidUIControl),例如设置/选择了参数值的TextBox。

Just be aware that you should be very defensive in your programming of queries like this to minimise the possibility of SQL injection attacks. 请注意,在对此类查询进行编程时应非常谨慎,以最大程度地减少SQL注入攻击的可能性。 Although the above will achieve what you want, you should probably look at replacing these text values with validated type-safe properties within the class though. 尽管以上内容可以实现您想要的结果,但是您可能应该考虑用类中经过验证的类型安全属性替换这些文本值。

Hope this helps? 希望这可以帮助?

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

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