Monday, February 20, 2012

My INSERT statements works... 8/10 times

I'm using the following code to add some data to a table:
Dim rand As Random = New Random
Dim num As Int32 = rand.Next(10000000)
Dim strConn as string = "......"
Dim sql as string = "INSERT INTO tblitemid (itemid, userid, datetime, supplier, comment, commenttype, uniqueid) VALUES ('" & label1.Text & "', '" & user.identity.name & "', '"& System.DateTime.Now & "','3763' ,'" & textbox1.text & "' , 'C' ,'" & num & "')"
Dim conn as New SQLConnection(strConn)
Dim Cmd as New SQLCommand(sql, conn)
Try
conn.Open()
Catch SQLExp as SQLException
Response.Write ("An SQL Server Error Occurred: " & e.toString())
Finally
cmd.ExecuteNonQuery
conn.Close()
End Try

As far as I can tell the code works fine. But for some odd reason I click the button, the code execute and the page closes as it should, but the data is never inserted into the database. I cant really seem to pick up on any paterns for why this would be happening. As a rough guess I'd say it doesnt insert the data 1 out of every 5 times or so it seems. Anyone every have any experience with this? Any comments would be helpful, cuz I'm at a loss.
If youd like to see more code let me know...
Thanks,
Scottscott, cmd.ExecuteNonQuery() should be in the try, not finally. because if you're getting an sql error, it'll error again when the cmd tries to execute w/o an open connection.

that's one. try stepping through it. Furthermore, don't use close, use conn.Dispose(), and cmd.Dispose(), and equal them to null.

Also, are you sure it's going through that part of the code?|||Are you sure all the vars have the correct data in them? I've not used the .net Rand function yet, should you be seeding it or you may get repeated numbers there too easily?|||I ended up getting it working, thanks guys. Turns out it was some javascript frather down in the code that was f'ing it all up.

No comments:

Post a Comment