select语句C#中的语法错误 [英] Syntax error in select statement C#
问题描述
我在执行以下代码时遇到问题(语法错误)。基本上我想查询SQL服务器的多个OR语句。请帮帮我,我该怎么办。谢谢。
数据库字段:pId,pAltId,pMobile,pDate,pName
变量:argID, alt_ID,p_mobile,p_date,p_Name
I am facing a problem in executing the below code (Syntax Error). Basically i want to query for a multiple OR statements for SQL server. Please help me what should i do. Thanks.
Database Fields: pId, pAltId, pMobile, pDate, pName
Variables:argID, alt_ID, p_mobile, p_date, p_Name
String selectStr = "select * from " + thisTable + " where pId = " + argID + " " + OR + " pAltId = " + alt_ID + " " + OR + " pMobile = " + p_mobile + " " + OR + " pDate = '" + p_date + "' " + OR + " pName = '" + p_Name + "'";
推荐答案
在ThePhantomUpvoter和Kenneth Haugland的评论中,你已经得到了很好的建议。
这是这个问题的一个很好的例子:< a href =http://xkcd.com/327/> http://xkcd.com/327/ [ ^ ]。
我会解释做什么。请参阅我过去的回答:
在com.ExecuteNonQuery()中重新启动EROR; [ ^ ],
你的名字没有显示名称? [ ^ ]。
-SA
You already got a good advice, in the comments to the question, by ThePhantomUpvoter and Kenneth Haugland.
This is a great example of this problem: http://xkcd.com/327/[^].
I''ll explain what to do instead. Please see my past answer:
EROR IN UPATE in com.ExecuteNonQuery();[^],
hi name is not displaying in name?[^].
—SA
String selectStr = "select * from " + thisTable + " where pId = " + argID + " OR pAltId = " + alt_ID +" OR pMobile = " + p_mobile +" OR pDate =" + p_date +" OR
pName = '"+ p_Name +"'"
更好用的是
Something better to use would be
SqlDataReader selectCommandResult = null;
try{
SqlCommand selectCommand = new SqlCommand("SELECT * FROM @table WHERE pId = @paramId OR pAltId = @paramAltId OR pMobile = @paramMobile OR pDate = @paramDate OR pName = @paramName", SqlConnectionHolder) { CommandType = CommandType.Text };
selectCommand.Parameters.AddWithValue("@table", thisTable);
selectCommand.Parameters.AddWithValue("@paramId", argID);
selectCommand.Parameters.AddWithValue("@paramAltId", alt_ID);
selectCommand.Parameters.AddWithValue("@paramMobile", p_mobile);
selectCommand.Parameters.AddWithValue("@paramDate", p_date);
selectCommand.Parameters.AddWithValue("@paramName", p_Name);
selectCommandResult = selectCommand.ExecuteReader();
var returnValue = "0";
//You should state what columns you wish to returns instead of using wild cards as table structures can change
while (selectCommandResult.Read())
{
columnOne = selectCommandResult.GetValue(0).ToString().Trim();
columnTwo = selectCommandResult.GetValue(1).ToString().Trim();
columnThree = selectCommandResult.GetValue(2).ToString().Trim();
//Etc...
}
}
catch (Exception ex){
throw ex;
}
我可能还建议您养成每个项目保留一个命名约定的习惯。 IE给出了以下变量名称:
thisTable
p_mobile
alt_ID
argID
应该是一个像这样的约定:
tbTableName
pMobileParam
pAltIdParam >
pArgIdParam
将来会更容易阅读。
进一步阅读: http://msdn.microsoft.com/en-us/library/ system.data.sqlclient.sqlcommand.aspx [ ^ ]
这篇关于select语句C#中的语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!