Select语句:无效的列名,在C#中使用Dapper,

问题描述 投票:0回答:1

这是我的数据库的模型类

public class Person
{
    public int id { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
    public string Fullinfo 
    { 
        get
        {
            return FirstName + " " + LastName + " " + Email;

        }
    }
}

这里是主班

public partial class DashBoard : Form
{
    List<Person> persons =new List<Person>();
    public DashBoard()
    {
        InitializeComponent();
        Updated();
    }

    public void Updated()
    {
        PeopleFoundListbox.DataSource = persons;
        PeopleFoundListbox.DisplayMember = "Fullinfo";
    }

    public void Searchpeoplebutton_Click(object sender, EventArgs e)
    {
        persons = Getpeople(Lastnametextbox.Text);
        Updated();

    }

    public List<Person> Getpeople(string searchname)
    {        
        using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.Cnn("peopleDb"))) 
        {
            var output = connection.Query<Person>("select * from People where Lastname= " + searchname).ToList();
            return output;
        }         
    }
}

我想根据姓氏选择记录我有一行使用大卫作为姓氏,但是每当我在文本框中键入大卫并搜索时,都会收到此错误

无效的列名称大卫

c# sql sql-server tsql dapper
1个回答
1
投票

基本上,您的查询缺少搜索名称周围的单引号。

此:

var output = connection.Query<Person>(
    "select * from People where Lastname= " + searchname
).ToList();

应该是:

var output = connection.Query<Person>(
    "select * from People where Lastname= '" + searchname + "'"
).ToList();

在没有单引号的情况下,SQL Server将文字字符串视为列名,因此会收到您收到的错误。

© www.soinside.com 2019 - 2024. All rights reserved.