Your connection object needs to be declared with a Using
in the method where it is used so it can be closed and disposed.
Use Using...End Using
blocks to ensure that your database objects are closed and disposed. Note the comma at the end of the Using
; this includes the command in the the Using
.
Pass the connection string directly to the constructor of the connection. Likewise, pass the CommandText
and the connection directly to the constructor of the command.
This should be .Add
method which takes the SqlDbType
as the second parameter. The .AddWithValue
method (which shouldn't be used with Sql Server) takes the value as the second parameter.
Never show a message box while a connection is open. The user could have gone to lunch and there sits your open connection. Actually, it will eventually time out but you get the point.
I hope the primary key of MULTIINSERT_TB is an identity field (auto-number) and you are not passing a value for it.
Private ConStr As String = "Your connection string"
Private Sub OpCode()
Try
Using con As New SqlConnection(ConStr),
com As New SqlCommand("insertooks", con)
com.CommandType = CommandType.StoredProcedure
com.Parameters.Add("@MULTIINSERT_CODE", SqlDbType.NVarChar).Value = TextBox1.Text
com.Parameters.Add("@MULTIINSERT_NAME", SqlDbType.NVarChar).Value = TextBox2.Text
com.Parameters.Add("@MULTIINSERT_DATE ", SqlDbType.Date).Value = DateTimePicker1.Value
con.Open()
com.ExecuteNonQuery()
End Using 'closes and disposes con and com
MsgBox("Record inserted successfully")
Catch ex As Exception
'Throw ex
MsgBox(ex.Message)
End Try
End Sub
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…