如何在C#中设置选择命令的嵌套 [英] how to set nested of select command in c#

查看:77
本文介绍了如何在C#中设置选择命令的嵌套的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在c#中运行以下命令时如何删除以下异常
DropDownList7有卡片,打印机等

how to remove following exception when I run below command in c#
DropDownList7 has card,printer etc

SqlCommand cmd = new SqlCommand("SELECT ItemName FROM ItemMaster where CategoryID=(SELECT CateoryID FROM Category where CategoryName= \"" + DropDownList7.SelectedItem.Text + "\" ) ", con);


When I compile it exception are
Invalid column name 'card'.
Invalid column name 'printer'.

推荐答案

error类没有操作remove. C#语言没有命令". 命令"的概念属于ADO.NET,但是您遇到的问题与SQL无关.看起来正确:您仅在行尾具有不平衡的;必须为"…)", con);".

很简单,不是吗?您的SQL的正确性仍在您身上. :-)

—SA
The error class has not operation remove. C# language does not have "commands". The concept of "command" belongs to ADO.NET, but the problem you have has nothing to do with SQL. Look properly: you simply has unbalanced " at the end of the line; must be "…)", con);".

Simple, isn''t it? The correctness of your SQL remains on you. :-)

—SA


请改用以下字符串:

Use the following string instead:

"SELECT ItemName FROM ItemMaster where CategoryID=(SELECT CateoryID FROM Category where CategoryName= \"" + DropDownList7.SelectedItem.Text +"\" )"


您在查询中使用双引号而不是单qoutes.请尝试以下代码.

You are using double quotes instead of single qoutes in your query. Please try the code below.

SqlCommand cmd = new SqlCommand("SELECT ItemName FROM ItemMaster where CategoryID=(SELECT CateoryID FROM Category where CategoryName = '" + DropDownList7.SelectedItem.Text + "' ) ", con);



您也不应内联编码参数,而应声明参数并将其添加到sql命令.上面的代码将打开您的应用程序以进行sql注入.而是尝试以下方法:



You should also not code your parameters inline, but rather declare and add parameters to your sql command. The code above will open your app to sql injection. Rather try this:

 SqlCommand cmd = new SqlCommand("SELECT ItemName FROM ItemMaster where CategoryID=(SELECT CateoryID FROM Category where CategoryName = @CategoryName) ", con);

SqlParameter prm = new SqlParameter("@CategoryName", SqlDbType.VarChar, 50);
prm.Direction = ParameterDirection.Input; 
prm.Value = DropDownList7.SelectedItem.Text; 
cmd.Parameters.Add(prm);


这篇关于如何在C#中设置选择命令的嵌套的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆