thormayer
thormayer

Reputation: 1070

Invalid column name exception

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 :)

Upvotes: 2

Views: 7972

Answers (2)

NG.
NG.

Reputation: 6043

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

Upvotes: 0

codingbiz
codingbiz

Reputation: 26386

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

Upvotes: 5

Related Questions