2

Im trying to get a simple SQL statement in my code, and get a DataTable, and for some reason I get this weird exception :

Invalid column name

This is my code :

public DataTable GetAllVideoID(string stringId)
    {
        dt = new DataTable();
        dataObj = new DataObj();
        sql = "SELECT * FROM TBL_VIDEOS WHERE TBL_VIDEOS.ID=" + stringId;

        return dt = dataObj.SelectDataTable(sql);
    }

public DataTable SelectDataTable(string sql)
    {
        try
        {
            conn = new SqlConnection(conString);
            conn.Open();
            adapter = new SqlDataAdapter(sql, conn);

            dt = new DataTable();

            adapter.Fill(dt);



            return dt;
        }
        catch (Exception e)
        {

            throw e;
        }
        finally { conn.Close(); }

    }

When I run this on my management tool, just the statemnet - it works perfectly. So I dunno ..

Structure of my DB : ID,TITLE,V_DESCIPTION,UPLOAD_DATE,V_VIEW,USERNAME,RATING,V_SOURCE,FLAG

thanks :)

thormayer
  • 1,070
  • 6
  • 28
  • 49

2 Answers2

5

changing your sql to

sql = "SELECT * FROM TBL_VIDEOS WHERE TBL_VIDEOS.ID='" + stringId+"'";

could fix this. That puts a single quote around the value of stringId e.g. .ID = '10'

If stringId = 'user' your query becomes

 sql = "SELECT * FROM TBL_VIDEOS WHERE TBL_VIDEOS.ID=user
 instead of
 sql = "SELECT * FROM TBL_VIDEOS WHERE TBL_VIDEOS.ID = 'user'

but user is not a valid variable in sql, so you get invalid column name

codingbiz
  • 26,179
  • 8
  • 59
  • 96
0

Your SelectDataTable method is absolutely fine. The only thing which comes to my mind is to replace this:

sql = "SELECT * FROM TBL_VIDEOS WHERE TBL_VIDEOS.ID=" + stringId;

by

sql = string.Format("SELECT * FROM TBL_VIDEOS WHERE TBL_VIDEOS.ID 
        = '{0}'", stringId);
M. Adeel Khalid
  • 1,786
  • 2
  • 21
  • 24
NG.
  • 5,695
  • 2
  • 19
  • 30