Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

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;
    }
like image 831
user3275745 Avatar asked Dec 29 '25 20:12

user3275745


1 Answers

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]"))
        }
    }
}
like image 149
Damith Avatar answered Jan 01 '26 10:01

Damith