admin

如何解决SQL查询C#中的最大长度错误(过长)

sql

我有一个包含sql语句的方法。它是

    public Boolean addRSS(string RSS_title, string Description, DateTime datetime, string RSS_Link, string user_name, float rate)
    {


        // Console.WriteLine(MyString.Remove(5, 10));
       // string a = date.ToString().Replace('.', '-');
        Boolean res = false;
        string sql = "INSERT INTO My_RSS ( RSS_Title,RSS_Description,RSS_Date,RSS_Link,RSS_Rate,UserName) values('" 
            +
            RSS_title + "','" +
            "FFFFFFFFFFFFFFFFFFFFFFFFFAAASDASDASDASD" +
            "', SYSUTCDATETIME(),'" +
            RSS_Link + "'," +
            rate + ",'"+
            user_name +  
            "')";
        try


        {


            // hasan = hasan.Insert(c, hasan);

            SqlCommand cmd = new SqlCommand(sql, Connect());
            cmd.ExecuteNonQuery();
            res = true;
        }
        catch (Exception)
        {
            res = false;
        }

        return res;

    }

它给人的错误,当我试图进入该输入http://rss.feedsportal.com/c/32727/f/510887/s/1da50441/l/0Lekonomi0Bmilliyet0N0Btr0Cenflasyon0Eyuzde0E50Ee0Einene0Ekadar0Esikacak0E0Cekonomi0Cekonomidetay0C210B0A30B20A120C15181930Cdefault0Bhtm/story01.htm到“链接栏”,它给错误,
‘e’附近的语法不正确。以“
Lekonomi0Bmilliyet0N0Btr0Cenflasyon0Eyuzde0E50Ee0Einene0Ekadar0Esikacak0E0Cekonomi0Cekonomidetay0C210B0A30B20A120C15181930Cdefau”开头的标识符过长。最大长度为128。字符串’)’后的右引号引起来。

另外,在sql端,此列是varchar(455)


阅读 235

收藏
2021-06-07

共1个答案

admin

错误是因为 标识符 名称太长;这与未关闭的引号引起的错误相结合,意味着您可能错过了开头的引号。也就是说,您有以下内容:

INSERT INTO Foo ( A ) VALUES ( AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA')

代替

INSERT INTO Foo ( A ) VALUES ( 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA')

您不应该通过字符串连接来构建查询。这是原因之一。参数化查询将为您提供正确的报价。(注意:您无需使用存储的proc即可使用参数化查询。)

var sql = "INSERT INTO My_RSS ( Title, Description, Date, Link, Rate, Name )
           VALUES ( @Title, @Desc, @PostDate, @Link, @Rate, @Name )";

SqlCommand cmd = new SqlCommand(sql, Connect());
cmd.Parameters.Add("@Title", SqlDbType.VarChar, 100).Value = RSS_title;
cmd.Parameters.Add("@Desc", SqlDbType.VarChar, 8192).Value = RSS_description;
cmd.Parameters.Add("@PostDate", SqlDbType.SmallDateTime).Value = DateTime.Now;
cmd.Parameters.Add("@Rate", SqlDbType.Int).Value = rate;

等等。

2021-06-07