【问题标题】:System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'file'System.Data.SqlClient.SqlException:关键字“文件”附近的语法不正确
【发布时间】:2014-02-05 15:07:40
【问题描述】:

我是 AsP.net 的新手,当我尝试使用常用代码连接到数据库时,一直显示异常,我不知道出了什么问题
例外是:

" System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'file'."

这是我的代码:

string ID = Request.QueryString["id"];

SqlCommand cmd = new SqlCommand("select title,file path,Upload Date from [Media] where ID=@id", conn);
cmd.CommandType = CommandType.Text;
SqlDataReader rdr=null;

try
{
    conn.Open();
    rdr = cmd.ExecuteReader();
    try
    {
        conn.Open();
        rdr = cmd.ExecuteReader();

        // print the CustomerID of each record
        while (rdr.Read())
        {
            pathTextBox.Text = rdr["file Path"].ToString();
            DateTextBox.Text = rdr["Upload Date"].ToString();
            titleTextBox.Text = rdr["title"].ToString();
        }

        Image1.ImageUrl = pathTextBox.Text;
    }

【问题讨论】:

  • 请出示您的SqlCommand
  • 我认为列名不应包含空格

标签: c# asp.net


【解决方案1】:

如果列名中有空格,则需要使用如下括号

select title,[file path],[Upload Date] from [Media] where ID=@id

using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
    conn.Open();
    cmd.CommandText = "select title,[file path],[Upload Date] from [Media] where ID=@id";
    cmd.Parameters.AddWithValue("@id", idval); // set the id parameter
    using (var reader = cmd.ExecuteReader())
    {
        if (reader.Read()) // you don't need while loop
        {
            pathTextBox.Text = reader.GetString(reader.GetOrdinal("[file path]"))
        }
    }
}

【讨论】:

  • 非常感谢它现在可以使用.....任何人都可以帮助我显示一个图像,该图像的路径是我从 ASP 图像查看器中的数据库中读取的路径
【解决方案2】:

如果您的列名包含空格(不推荐),您应该使用方括号,例如[]。例如[Upload Date]

列名必须遵循标识符规则。

来自Database Identifiers

SELECT *
FROM [My Table]      --Identifier contains a space and uses a reserved keyword.
WHERE [order] = 10   --Identifier is a reserved keyword.

这就是为什么你应该像这样使用它们;

select title,[file path],[Upload Date]

此外,您不要在代码中的任何位置添加参数值。

SqlCommand cmd = new SqlCommand("select title,[file path],[Upload Date] from Media where ID=@id", conn);
cmd.Parameters.AddWithValue("@id", YourIDValue);

还可以使用using statement 来处理您的SqlConnectionSqlCommand

using (SqlConnection conn = new SqlConnection(YourConnectionString))
{
   using (SqlCommand cmd = new SqlCommand())
   {
      //Your code..
   }
}

【讨论】:

    猜你喜欢
    • 2015-10-10
    • 2021-07-24
    • 2021-11-22
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    • 2021-03-31
    • 2019-07-17
    相关资源
    最近更新 更多