c# - 数据类型 text 和 varchar 在 C# 中的等于运算符中不兼容

标签 c#

我正在尝试从 employeeTable 访问数据 empname,但我编写的代码出现以下错误:

The data types text and varchar are incompatible in the equal to operator.

请提出解决方案

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    string Connection = "Data Source=(local);Initial catalog=Test;Integrated Security=true";
    string Query = "SELECT * FROM  EmployeeTable WHERE empname='" + comboBox1.Text + "' ;";

    SqlConnection conn = new SqlConnection(Connection);
    SqlCommand cmd = new SqlCommand(Query, conn);

    conn.Open();
    SqlDataReader reader = cmd.ExecuteReader();

    while (reader.Read())     
    {
        textBoxEmpName.Text = reader["EmpName"].ToString();
    }
}

最佳答案

您不能将 text 与 varchar 进行比较,但作为对将来遇到此问题的任何人的回答,只需将 text 列转换为 varchar 以进行查询。

SELECT * FROM  EmployeeTable WHERE CONVERT(VARCHAR, empname) = '" + comboBox1.Text + "' ;";

始终使用 parameters

SELECT * FROM  EmployeeTable WHERE CONVERT(VARCHAR, empname) = @comboBox";

关于c# - 数据类型 text 和 varchar 在 C# 中的等于运算符中不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27888243/

相关文章:

c# - 将 dll 添加到引用后,类库 Intellisense 未显示

c# - 从 ASHX 将 PDF 返回到网页

c# - JSON 列表转换器 C#

c# - 使用反射的 Dapper 与 ADO.Net 哪个更快?

c# - Automapper:对所有其他成员使用默认映射

c# - Entity Framework 访问数据库方法

c# - MvvmCross - MvxListView绑定(bind)多次点击

c# - 链式 GZipStream/DeflateStream 和 CryptoStream (AES) 在读取时中断

c# - 局域网宠物项目

c# - 为什么不同版本的 Visual Studio 会输出相同代码的不同结果?