Take the following example...
Using cn As New SqlConnection(ConnectionString)
Try
Dim cmd As SqlCommand = New SqlCommand
With cmd
.Connection = cn
.Connection.Open()
.CommandText = "dbo.GetCustomerByID"
.CommandType = CommandType.StoredProcedure
.Parameters.Add("#CustomerID", SqlDbType.Int, 4)
.Parameters("#CustomerID").Value = CustomerID
End With
da = New SqlDataAdapter(cmd)
da.Fill(ds, "Customer")
Catch ex As Exception
End Try
End Using
From my research today is sounds as though this is basically okay but the SqlCommand is not being disposed of.
Question -> Which of the following examples is the best way to deal with this?
Example 2 - Dispose manually
Using cn As New SqlConnection(ConnectionString)
Try
Dim cmd As SqlCommand = New SqlCommand
With cmd
.Connection = cn
.Connection.Open()
.CommandText = "dbo.GetCustomerByID"
.CommandType = CommandType.StoredProcedure
.Parameters.Add("#CustomerID", SqlDbType.Int, 4)
.Parameters("#CustomerID").Value = CustomerID
End With
da = New SqlDataAdapter(cmd)
cmd.Dispose()
da.Fill(ds, "Customer")
Catch ex As Exception
End Try
End Using
Example 3 - Automatic disposing with the Using statement
Using cn As New SqlConnection(ConnectionString)
Try
Using cmd As New SqlCommand
With cmd
.Connection = cn
.Connection.Open()
.CommandText = "dbo.GetCustomerByID"
.CommandType = CommandType.StoredProcedure
.Parameters.Add("#CustomerID", SqlDbType.Int, 4)
.Parameters("#CustomerID").Value = CustomerID
End With
da = New SqlDataAdapter(cmd)
da.Fill(ds, "Customer")
End Using
Catch ex As Exception
End Try
End Using
Example 4 - The same as example 3 but the Try/Catch is within the Using - does this make a difference?
Using cn As New SqlConnection(ConnectionString)
Using cmd As New SqlCommand
Try
With cmd
.Connection = cn
.Connection.Open()
.CommandText = "dbo.GetCustomerByID"
.CommandType = CommandType.StoredProcedure
.Parameters.Add("#CustomerID", SqlDbType.Int, 4)
.Parameters("#CustomerID").Value = CustomerID
End With
da = New SqlDataAdapter(cmd)
da.Fill(ds, "Customer")
Catch ex As Exception
End Try
End Using
End Using
Example 5 - The same as example 4 but the CommandText and cn are specified in the Using Statement - What advantage does this have?
Using cn As New SqlConnection(ConnectionString)
Using cmd As New SqlCommand("GetCustomerByID", cn)
Try
With cmd
.Connection.Open()
.CommandType = CommandType.StoredProcedure
.Parameters.Add("#CustomerID", SqlDbType.Int, 4)
.Parameters("#CustomerID").Value = CustomerID
End With
da = New SqlDataAdapter(cmd)
da.Fill(ds, "Customer")
Catch ex As Exception
End Try
End Using
End Using
Example 6 - The same as example 5 but the connection is opened on cn instead of cmd. Is it better to open the connection on cmd if only one stored procedure is to be executed?
Using cn As New SqlConnection(ConnectionString)
cn.Open()
Using cmd As New SqlCommand("GetCustomerByID", cn)
Try
With cmd
.Connection = cn
.CommandType = CommandType.StoredProcedure
.Parameters.Add("#CustomerID", SqlDbType.Int, 4)
.Parameters("#CustomerID").Value = CustomerID
End With
da = New SqlDataAdapter(cmd)
da.Fill(ds, "Customer")
Catch ex As Exception
End Try
End Using
End Using
The DataAdapter.Fill command will open and close the connection itself, so you don't need the cmd.Connection.Open(). (Ref: the remarks section in http://msdn.microsoft.com/en-us/library/377a8x4t.aspx .)
Using Using for the SqlConnection has the effect of calling .Close on it for you.
The variable cmd becomes eligible for garbage collection once it is out of scope (or earlier if .NET determines it isn't going to be used again).
In your example 2, I'm not sure it's such a good idea to dispose of the cmd before the DataAdapter has used it.
[Information from user "JefBar Software Services" in Should I call Dispose on a SQLCommand object? ] At the time of writing, calling .Dispose on an SqlCommand has no effect because of the code in its constructor:
public SqlCommand() : base() {
GC.SuppressFinalize(this);
}
Related
Dim sc = datagridview.rows(0).cells(0).value
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters.AddWithValue("#sc", sc.cells(0))
end with
The value from the datagrid view contains an apostrophe where I get an error in ('s). Any work around with this?
EDIT:
This is the error:
SqlException was unhandled. Incorrect syntax near 's'.
EDIT 2: i've revised the code to this:
for 1=0 to datagridview.rows.count -1
Dim tname = datagridview.Rows(i)
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters.AddWithValue("#sc", sc.cells(0).value)
end with
con.Close()
con.Open()
If Not cmd.ExecuteNonQuery() > 0 Then
con.Close()
Exit For
End If
next
Error is still the same.
As it goes through all the values quickly in one go, I would make the connection once and change the value of the parameter for each iteration, like this:
Dim sql = "INSERT INTO [Schedule] ([Name]) VALUES(#sc)"
Using conn As New SqlConnection("your connection string"),
cmd As New SqlCommand(sql, conn)
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#sc",
.SqlDbType = SqlDbType.NVarChar,
.Size = -1})
conn.Open()
For i = 0 To dgv.Rows.Count - 1
Dim tname = dgv.Rows(i).Cells(0).Value.ToString()
cmd.Parameters("#sc").Value = tname
cmd.ExecuteNonQuery()
Next
End Using
Including the size of the parameter in its declaration helps SQL Server keep things tidy (it only needs one entry in the query cache).
The Using statement makes sure that the connection and command are disposed of properly when they are finished with.
The purpose of checking If Not cmd.ExecuteNonQuery() > 0 was not clear to me, so I didn't put that in.
(I used "dgv" as the name of the DataGridView.)
Try to replace the " ' " by " '' "
Dim sc = datagridview.rows(0).cells(0).value
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters.AddWithValue("#sc", replace(sc.cells(0), "'", "''")
end with
/**** EDIT ****/
I will consider by the way that your code have a problem with the affectation of the value. You get the value into SC then try to get again the value from cell
Dim sc = datagridview.rows(0).cells(0).value
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters("#sc").value = sc.replace("'", "''")
end with
Trying to save all rows in DataGridView using For Each loop and the application sometimes freezes while I am not saving any rows. How can I solve this problem?
Using con As New SqlConnection(cs)
Using cmd As New SqlCommand
con.Open()
cmd.CommandTimeout = 120
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "[Stored_invoice]"
cmd.Parameters.Clear()
cmd.Connection = con
For Each row As DataGridViewRow In dgwold.Rows
If Not row.IsNewRow Then
If IsDBNull(row.Cells(6).Value) Then
xv = row.Cells(6).Value
Else
xv = DBNull.Value
End If
cmd.Parameters.AddWithValue("#Action", 0)
cmd.Parameters.AddWithValue("#invoice_id", invid)
cmd.Parameters.AddWithValue("#ExpireDate", xv)
cmd.Connection = con
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
End If
Next
I am trying to run a query/job and need to wait until the job/query is done running to continue onto the next line of code in the VB.NET application. How would I do this?
con.Open()
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = con
cmd.CommandText = "USE msdb; EXEC dbo.sp_start_job N'FWP1 Incremental Daily'"
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
con.Close()
(WAIT UNTIL FINISHES) - How do I Code this???
\\Continue Code...........
Application.UseWaitCursor = True
con.Open()
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = con
cmd.CommandText = "USE msdb; EXEC dbo.sp_start_job N'FWP1 Incremental Daily'"
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
con.Close()
Application.UseWaitCursor = False
MsgBox("Finished!")
Hope this will help.
I have this code that populates a datagridview with data from ms access:
Dim con As New OleDbConnection
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim Sql As String
Sql = "SELECT * FROM myTable WHERE case_no=?"
Try
con.ConnectionString = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source=Sample.accdb;Persist Security Info=True;Jet OLEDB:Database Password=dbadmin2010"
con.Open()
Dim cmd As OleDbCommand = New OleDbCommand(Sql, con)
da.SelectCommand = cmd
cmd.Parameters.AddWithValue("case_no", case_no)
Dim ds As DataSet = New DataSet
da.Fill(ds, "Case Info")
DataGridView1.DataSource = ds.Tables("Case Info")
Catch ex As Exception
MsgBox(ex.Message)
End Try
Now I had just finished creating a query from design view within MS Access itself, is there a way to call that query and retrieve the results to my datagridview?
Just use the query name and set the command type, for example, in addition to what you already have, you can use the following notes:
Try
con.ConnectionString = enter_connection_string_here
con.Open()
cmd.Connection = con
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "NameOfQuery"
da.SelectCommand = cmd
cmd.Parameters.AddWithValue("case_no", case_no)
da.Fill(ds, "Case Info")
As you can probably very soon see, I am a complete newbie at VB.NET, and I am having some trouble getting output from a stored procedure in SQL Server 2005.
This is the code I use
Dim con As New SqlConnection
Dim cmd As New SqlCommand("esp_getDates", con)
Dim par As New SqlParameter("#PlaceID", SqlDbType.Int, 3906)
con.ConnectionString = "Data Source=localhost\SQLEXPRESS;Initial Catalog=ProgramDB;User ID=test;Password=test"
con.Open()
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters("#PlaceID").Direction = ParameterDirection.Output
cmd.ExecuteNonQuery()
con.Close()
I get the error;
An SqlParameter with ParameterName
'#PlaceID' is not contained by this
SqlParameterCollection.
Does anyone see what I'm doing wrong / have any suggestions how I can fix it? Code examples would be very helpful and any help is much appreciated.
You aren't actually adding the parameter to the cmd.Parameters collection:
cmd.Parameters.Add(par)
Alternatively, just add the parameter without instantiating the Parameter object explicitly:
cmd.Parameters.Add("#PlaceID", SqlDbType.Int)
cmd.Parameters("#PlaceID").Value = 3906
Also, I'd follow the principle of using a variable as close to the declaration as possible and reorganize things this way:
Dim con As New SqlConnection("Data Source=localhost\SQLEXPRESS;Initial Catalog=ProgramDB;User ID=test;Password=test")
con.Open()
Dim cmd As New SqlCommand("esp_getDates", con)
Try
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#PlaceID", SqlDbType.Int)
cmd.Parameters("#PlaceID").Value = 3906
cmd.ExecuteNonQuery()
Finally
If cmd IsNot Nothing Then cmd.Dispose()
If cn IsNot Nothing AndAlso cn.State <> ConnectionState.Closed Then cn.Close()
End Try