我真的很困惑为什么我的脚本总是会给出错误结果 我想使用多个条件
来制作' if section ' 像这样string kalimatsql2 = "SELECT ID FROM Questions WHERE (content = '" + var + "'" + " && Quiz_ID = '" + idQuiz + "')";
我已尝试更改单引号,将=
更改为==
,将()
更改为dll
但仍然给出错误
查询表达式中的语法错误(缺少运算符)'(content ='test2'&&" Quiz_ID ='6')'。
更新
string kalimatsql2 = "SELECT ID FROM Questions WHERE (content = '" + dataDel + "'" + " AND Quiz_ID = " + idQuiz + ")";
int idQuestion = sqlReader(kalimatsql2);
这是sqlReader函数的代码
private int sqlReader( string kalimatSql)
{
Global.dbCon.Open();
List<int> idQuestions = new List<int>();
Global.reader = Global.riyeder(kalimatSql);
if (Global.reader.HasRows)
{
while (Global.reader.Read())
{
int idQuestion = Convert.ToInt32(Global.reader.GetValue(0));
idQuestions.Add(idQuestion);
}
}
Global.dbCon.Close();
foreach (int id in idQuestions) {
return id;
}
return (idQuestions.Count > 0) ? idQuestions[0] : -1;
}
我使用microsoft access作为数据库
答案 0 :(得分:11)
您似乎在混合使用LINQ和SQL。
将&&
替换为AND
。
如果它实际上是一个数字而不是一个字符串,你可能还必须从idQuiz周围删除单个撇号。
此外,我们无法看到您的其余代码,但您需要查看参数化查询,而不是将它们连接成一个字符串。它更安全,更易于阅读和维护。
这是即时的,因此可能存在一些语法错误。它并不完全符合你的例子 - 我不确定你在Global
类中有什么样的逻辑。
private int GetQuestionIds(string content, int quizId)
{
List<int> idQuestions = new List<int>();
string query
= "SELECT ID FROM Questions WHERE (content = @content AND Quiz_ID = @quizId)";
using (var connection = new SqlConnection(connectionString))
{
var command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@content", content);
command.Parameters.AddWithValue("@quizId", quizId);
try
{
connection.Open();
var reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
int idQuestion = Convert.ToInt32(Global.reader.GetValue(0));
idQuestions.Add(idQuestion);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return idQuestions.Any() ? idQuestions.First() : -1;
}
您可以在MSDN找到更多信息。