SQL LIKE查询到c#代码
本文关键字:代码 查询 LIKE SQL | 更新日期: 2023-09-27 17:50:59
我需要在我的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'"
假设您使用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);
有三个问题。
- 代码值和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%'");
}
字符字段使用单引号。
"SELECT AVG(Percentage) FROM MasterTable WHERE Code LIKE '" + comboBoxSubject.Text +
"' AND Year LIKE '" + dateTimePicker1 + "' AND Sitting LIKE 'June'"
使用%
和'
和请考虑使用参数:
SELECT AVG(Percentage) FROM MasterTable WHERE (Code LIKE '%' + @text + '%')
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);