得到错误“''''附近的语法不正确 [英] getting the error "Incorrect syntax near '='"

查看:116
本文介绍了得到错误“''''附近的语法不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在txtdate1中传递日期时,它给出了错误

,当我在两个文本框中都传递日期时,它会给出错误'之间的错误语法'

when i pass date in txtdate1 it give me the error
and when i pass date in both textbox then it give me the error "Incorrect syntax near 'between'

string search = "SELECT Id,Category,Subject,Date FROM News ";
if (txtdate1.Text != "" && txtdate2.Text != "")
{
    search = search + "Where Date between '" + date1 + "' and '" + date2 + "'";
}
else if (txtdate1.Text != "" && txtdate2.Text == "")
{
    search = search + "Where Date = '" + date1 +  "'";
}
else if (txtdate2.Text != "")
{
    search = search + "Where Date = '" + date2 + "'";
}
cmd.CommandText = search;
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
gvImages.DataSource = ds;
gvImages.DataBind();

推荐答案

问题源于你没有使用参数。您永远不应该将值直接连接到SQL语句,而是使用参数。连接值引入了这种转换问题,但也让您对SQL注入有了广泛的开放(参见 SQL注入) [ ^ ]



有关详细信息,请参阅 SqlParameter类 [ ^ ]
The problem originates from the fact that you're not using parameters. You should never concatenate values directly to the SQL statement but use parameters instead. Concatenating values introduces this kind of conversion problems but also leaves you wide open to SQL injections (see SQL Injection)[^]

For more information see SqlParameter Class[^]


你应该做的第一件事是在尝试但在你的SQL查询之前,用DateTime从文本框中解析文本。或者甚至更好地使用DatePickers,它将为您提供DateTime对象。

其次,由于用户错误和注入攻击,不应在字段中添加字段到您的查询。它们应该作为参数添加,并确保它们是正确的SQL数据类型。



SQL查询看起来就像是在使用MySQL。字符串只需要撇号吗?
First thing you should do is Parse the Text from the textboxes with DateTime before trying to but in you SQL query. Or even better use DatePickers which will give you a DateTime object.
Secondly, fields should never be added in-line to your query because of user errors and injection attacks. They should be added as parameters and make sure they are the correct SQL data type.

The SQL is query looks like you're using MySQL. Isn't apostrophe only needed for strings?


这篇关于得到错误“''''附近的语法不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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