Link to home
Start Free TrialLog in
Avatar of g_johnson
g_johnsonFlag for United States of America

asked on

what is wrong with this code -- sql query thru command object

this returns the error "Referenced object has a value of nothing" on the line rdr1 = cm1.executereader

I'm guessing it has to do with how I do parameters?


        Try
            c1 = New SqlConnection
            c1.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings("Connection")
            c1.Open()

            cm1 = New SqlCommand
            cm1.CommandType = CommandType.Text
            cm1.Connection = c1
            cm1.CommandText = "SELECT desc [d] FROM table1_sql WHERE item = ? ORDER BY fn"
            cm1.Parameters.Add("@Desc", SqlDbType.Char, 15, txtItem.Text)
            rdr1 = cm1.ExecuteReader
            While rdr1.Read
                lstFtr.Items.Add(CType(rdr1("d"), String))
            End While
            rdr1.Close()

            c1.Close()

        Catch ex As Exception

        End Try
Avatar of g_johnson
g_johnson
Flag of United States of America image

ASKER

actually, the more i investigate the more i think it's a syntax error.

obviously i am doing something wrong when adding parameters, but i don't know what it is
Avatar of Éric Moreau
Hi g_johnson,

Is "desc" your field name? I think the problem lies there because "desc" is a reserved word (of the ORBER BY clause). Try putting it in square brakets like you did for the alias.

Cheers!
g_johnson,

and what happen if you don't use a parameter?  
if i don't use a parameter, i'm fine
this is the actual line of code:
cm1.CommandText = "SELECT description_1 [d] FROM table1_sql WHERE item = ? ORDER BY fn"
and ex.message returns
"Line 1: Incorrect syntax near '?'."
ASKER CERTIFIED SOLUTION
Avatar of Éric Moreau
Éric Moreau
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
got it -- just before I read your answer.  Now I understand!   :-)

Thanks