C#和SQL问题 [英] C# & SQL problem

查看:124
本文介绍了C#和SQL问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



每当我尝试更改dropdownlist1索引值时,都会出现此错误,该值只有两个值:销售和租金. "="附近的语法不正确"

有人可以帮我吗?
-------------------

Hi,

I get this error every time I try to change the dropdownlist1 index value which are only two values, sale and rent; "incorrect syntax near ''=''"

Could someone help me please?
-------------------

string select;
        select = "SELECT * FROM Property";
        select += "WHERE Sale_Rent=''" + DropDownList1.SelectedItem.Value.ToString() + "''";
        SqlConnection connect1 = new SqlConnection(connectionString);

        SqlCommand myCommand = new SqlCommand(select, connect1);

       
        SqlDataReader readIt;

        try
        {
            connect1.Open();//make connection

            readIt = myCommand.ExecuteReader();

            while (readIt.Read())
            {
                ListItem newItem = new ListItem();
                newItem.Text = readIt["Address"].ToString();
                newItem.Value = readIt["Property_ID"].ToString();
                box1.Items.Add(newItem);
            }
            readIt.Close();
        }

推荐答案

语法错误是因为您需要在属性"和"WHERE"之间留一个空格-在您的select语句求值结果为:
The syntax error is because you need a space between "Property" and "WHERE" - at the moment your select statement evaluates to:
"SELECT * FROM PropertyWHERE Sale_Rent=''Rent''"



另外:
1)使用ASP.NET而不是C#标记问题-ASP.NET外部不存在具有Value属性的DropDownList.
2)尝试养成使用参数化查询的习惯:我知道您现有的代码没有SQL注入攻击的风险,但是当您在一个月内为您的文本框重新使用此代码时,您不会认为关于它.值得早日养成习惯,并始终使用它.
3)为什么不尝试使用调试器?那会在三十秒内向您显示问题!



In addition:
1) Tag your question with ASP.NET, rather than C# - a DropDownList with a Value property does not exist outside ASP.NET.
2) Try to get into the habit of using parameterized queries: I know that your existing code has no risk of an SQL Injection attack, but when you re-use this code in a month for you text box, you won''t think about it. It is well worth getting into the habit early, and using it at all times.
3) Why didn''t you try using the debugger? That would have shown you the problem in thirty seconds!


您好,
选择+ ="WHERE Sale_Rent =""+ DropDownList1.SelectedItem.Value.ToString()+"'';

更改以上行为

选择+ ="WHERE Sale_Rent =""+ DropDownList1.SelectedValue.ToString()+"";
Hello,
select += "WHERE Sale_Rent=''" + DropDownList1.SelectedItem.Value.ToString() + "''";

change of above line as

select += "WHERE Sale_Rent=''" + DropDownList1.SelectedValue.ToString() + "''";


Property和SQL语句中的位置之间没有空格.那一定是导致错误的原因.
There is no space between Property and Where in your SQL statement. That must be causing the error.


这篇关于C#和SQL问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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