c# - "An expression of non-boolean type specified"从 .Net 执行 SQL 时出错

标签 c# sql .net sqlclient

我收到这个错误:

An expression of non-boolean type specified in a context where a condition is expected, near 'likeram'.

我在 txt_name 中输入了“ram”:

SqlConnection con = new SqlConnection(
                @"Data Source=DELL_LAPTOP\sqlexpress;Integrated Security=True");
DataTable dt = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter(
                    "SELECT * FROM newproj where name like" + txt_name.Text, con);
SDA.Fill(dt);
dataGridView1.DataSource = dt;

最佳答案

like 和字符串连接以及参数两边的引号之间缺少空格:

SqlDataAdapter SDA = new SqlDataAdapter(
               string.Format("SELECT * 
                              FROM newproj 
                              WHERE name like '{0}'" txt_name.Text), con);

虽然我建议您不要使用该方法,因为它容易出现 SQL 注入(inject)。改用 SQL 参数:

SqlCommand command = new SqlCommand("SELECT * FROM newproj where name like @text");
command.Parameters.AddWithValue("text", txtName.Text);
var sqlAdapter = new SqlDataAdapter(command);

关于c# - "An expression of non-boolean type specified"从 .Net 执行 SQL 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31830311/

相关文章:

c# - 如何在运行时更改OData EDM模型

c# - 使用 P/Invoke 调用带有 char* 参数的 C DLL 函数

c# - Server.Transfer 在 C# 代码中。服务器在当前上下文中不存在

sql - 我需要在 Oracle 上的外键上创建索引吗?

java - oracle Jdbc更新语句返回零

c# - PnP WPF/Silverlight 复合应用程序指南是否适合基于角色的 UI 组合?

c# - ASP.NET 图表助手的自定义标题字体

c# - LINQ to SQL - 排序依据、分组依据以及每个组的排序,并带有skip和take

mysql - MySQL 中会自动索引唯一键 - 这是真的吗?

.net - Exchange 2003-使用哪个API找出房间/资源的可用性?