运行SQL Server查询时出现C#异常错误

时间:2019-06-01 18:45:41

标签: c# sql-server

我正在构建简单的库应用程序。我正在使用C#和SQL Server 2017。

在运行功能来检查图书是否已经存在时,我在“名称”附近收到错误消息。

        public bool DoesItExist()
        {
            mainSet mset = new mainSet();
            string query = "SELECT * FROM [Library].[dbo].[ViewBook] WHERE " +
                "Title = '" + this.title + "' AND " +
                "DateOfFirstRelease = " + this.release_date + " AND " +
                "Name = '" + this.author_name + "' AND " +
                "2Name= '" + this.author_2name + "' AND " +
                "Surname = '" + this.author_surname + "' AND " +
                "Category = '" + this.category + "' AND " +
                "Publishing = '" + this.Publishing+ "' ";

            SqlConnection cnn = new SqlConnection(mset.dataBaseConect);
            SqlCommand cmd = new SqlCommand(query, cnn);
            cnn.Open();
            SqlDataReader reader = cmd.ExecuteReader();  

            if (reader.HasRows) return true;
            else return false;
        }

所有“ this。” 都是“ Title”类中的参数。

除“ DateOfRelease”类型为:int

外,所有参数均为类型:字符串

[ViewBook]是[Library]数据库中的视图。

我遇到的错误:

System.Data.SqlClient.SqlException: 

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

cmd查询示例:

"SELECT * FROM [Library].[dbo].[ViewBook] WHERE Title = 'Book Name' AND DateOfFirstRelease = 2004 AND Name = 'George' AND 2Name= '' AND Surname = 'Martin' AND Category = 'Economy' AND Publishing = 'PublishingTest' "

1 个答案:

答案 0 :(得分:1)

这个答案有一个警告。我不是c#编码器,所以我没有测试过。我很少接触C#,仅当我这样做时,是因为我正在协助我们的开发人员满足他们的SQL Server要求(因为我是DBA / SQL开发人员)。我怎么办我使用文档(SqlDbType Enum和{{3}})编写了一个参数正确的查询,该查询应该有效(我添加了关于为什么相信的注释您的查询也失败了):

Environment