简体   繁体   中英

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

i'm new to AsP.net when i'm trying my usual code to connect to database there's exception keep shown and idon't know what's wrong
the exception is :

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

and this my code :

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

If your column names contains white space (which is not recomended) you should use square brackets like [] . For example, [Upload Date]

Column names must follow the rules for identifiers.

From Database Identifiers

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

That's why you should use them like;

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

Also you don't add your parameter value anywhere in your code.

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

Also use using statement to dispose your SqlConnection and SqlCommand .

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

if you have spaces in column names you need to use brackets like below

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]"))
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM