System.Data.SqlClient.SqlException:关键字'file'附近的语法不正确

时间:2014-02-05 15:07:40

标签: c# asp.net

我是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;
    }

2 个答案:

答案 0 :(得分:1)

如果您的列名称包含空格(不建议使用),则应使用方括号,例如[]。例如,[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..
   }
}

答案 1 :(得分: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]"))
        }
    }
}