gpt4 book ai didi

c# - if 语句有 2 个条件

转载 作者:行者123 更新时间:2023-11-30 19:09:53 25 4
gpt4 key购买 nike

我真的很困惑为什么我的脚本总是给出错误结果我想制作具有多个条件

的“ if section

像这样

string kalimatsql2 = "SELECT ID FROM Questions WHERE (content = '" + var + "'" + " && Quiz_ID = '" + idQuiz + "')";

我已经尝试过更改单引号,将=更改为==,省略(),dll但是还是报错

Syntax error (missing operator) in query expression '(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;
}

我用微软access做数据库

最佳答案

您似乎在混合使用 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 上找到更多信息.

关于c# - if 语句有 2 个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21567262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com