Wednesday, March 21, 2012

ExecuteReader: Connection property has not been initialized.

I have a web form that is generating an error and I can't seem to figure out why for the life of me. Below is the code:


Private Sub VerifyNoDuplicateEmail()
Dim conn As SqlConnection
Dim sql As String
Dim cmd As SqlCommand
Dim id As Guid
sql = "Select UserID from SDCUsers where email='{0}'"
sql = String.Format(sql, txtEmail.Text)
cmd = New SqlCommand(sql, conn)
conn = New SqlConnection(ConfigurationSettings.AppSettings("cnSDCADC.ConnectionString"))
conn.Open()
Try
'The first this we need to do here is query the database and verify
'that no one has registed with this particular e-mail address
id = cmd.ExecuteScalar()
Response.Write(id.ToString & "<BR>")
Catch
Response.Write(sql & "<BR>")
Response.Write("An error has occurred: " & Err.Description)
Finally
If Not id.ToString Is Nothing Then
'The e-mail address is already registered.
Response.Write("Your e-mail address has already been registered with this site.<BR>")
conn.Close()
_NoDuplicates = False
Else
'It's safe to add the user to the database
conn.Close()
_NoDuplicates = True
End If
End Try
End Sub

Web.Config
<appSettings>
<!-- User application and configured property settings go here.-->
<!-- Example: <add key="settingName" value="settingValue"/> -->
<add key="cnSDCADC.ConnectionString" value="workstation id=STEPHEN;packet size=4096;integrated security=SSPI;data source=SDCADC;persist security info=False;initial catalog=sdc" />
</appSettings>

Can anyone show me the error of my ways?

Thanks,
StephenPlease elaborate on "generating an error". An exact error mesage will probably go a long way in helping you correct your problem.

Also, please use parameters and not string concetenation to build your SQL commands!!

Instead of this:


sql = "Select UserID from SDCUsers where email='{0}'"
sql = String.Format(sql, txtEmail.Text)
cmd = New SqlCommand(sql, conn)

do something like this:

sql = "Select UserID from SDCUsers where email=@.email"
cmd = New SqlCommand(sql, conn)
cmd.Parameters.Add(New SqlParameter("@.email", SqlDbType.VarChar, 99)).Value = txtEmail.Text

Terri|||Terri,

The exact error is the title of the thread "ExecuteReader: Connection property has not been initialized."

Thanks,

Stephen|||Terri,

I tried the changes you suggested and still recieved the same error. After taking a little time off and coming back the to the problem I finally found the error of my ways. I was initializing the CMD object before the CONN object. Thanks for you help.

Stephen|||Oh yes, so you were. :-)

Please use parameters anyway -- that suggestion was something of an aside. And next time you post please include the error message. We could have helped you a lot quicker with that information!

Terri

No comments:

Post a Comment