2

我需要在我的 C# 代码中使用以下查询:

SELECT AVG(Percent) 
From Table1
Where code Like "Sport" and Year Like"2011" and Sitting Like"June";

我是这样做的:

"SELECT AVG(Percentage) FROM MasterTable WHERE Code LIKE " + comboBoxSubject.Text +
"AND Year LIKE "+dateTimePicker1 +" AND Sitting LIKE June"

但我得到一个例外可能是因为参数是从不同的控件中提取的并且没有放在引号中。

谁能帮我 ?

回答

这是对我有用的查询:

"SELECT AVG(Percent) FROM MasterTable WHERE Code LIKE '" + comboBoxSubject.Text + "' AND Year LIKE '" + dateTimePicker1.Value.Year + "' AND Sitting LIKE 'June'"
4

5 回答 5

5

假设您使用 SQLite,因为您没有提及任何数据库。这就是避免 SQL 注入的方法。

var selectCommand = new SQLiteCommand("@SELECT AVG (PERCENT) 
                                       FROM TABLE1
                                       WHERE CODE LIKE @sport AND YEAR LIKE @year AND SITTING LIKE @month");
selectCommand.Parameters.AddWithValue("@sport", sportParameter);
selectCommand.Parameters.AddWithValue("@year", yearParameter);
selectCommand.Parameters.AddWithValue("@month", monthParameter);
于 2013-01-08T19:57:54.827 回答
2

存在三个问题。

  • 代码值和 AND 后没有空格
  • 值之间缺少单引号
  • SQL LIKE 语句中缺少通配符 (%)

这取决于您正在从事哪种项目,但我经常发现通过打印最终查询来发现语法错误和缺少空格要容易得多。例如,下面是执行此操作的控制台应用程序。

static void Main(string[] args)
{
    const string code = "Sport";
    const string year = "2011";
    Console.WriteLine("SELECT AVG(Percentage) FROM MasterTable WHERE Code LIKE '%" + code + "%' AND Year LIKE '%" + year + "%' AND Sitting LIKE '%June%'");
}
于 2013-12-17T22:12:02.013 回答
1

使用%and'考虑使用参数

SELECT AVG(Percentage) FROM MasterTable WHERE (Code LIKE '%' + @text + '%')
于 2013-01-08T19:56:15.453 回答
1

对字符字段使用单引号。

"SELECT AVG(Percentage) FROM MasterTable WHERE Code LIKE '" + comboBoxSubject.Text +
        "' AND Year LIKE '" + dateTimePicker1 + "' AND Sitting LIKE 'June'"
于 2013-01-08T19:56:45.133 回答
0
MySqlCommand cmd = new MySqlCommand("SELECT Employee_No, Image, Last_Name, First_Name, Middle_Name, Suffix, Sex, Birthdate, Contact_No, Address, Username FROM user_tbl WHERE Employee_No LIKE '%" + searchemployeeno + "%' OR Last_Name LIKE '%" + searchemployeeno + "%' ", SQLConn.conn);
于 2020-02-18T16:02:07.793 回答