sqlcommand timeout using looping vb.net - sql-server

may this code explain my problem,
dim dgv1 as new datagridview
dim dgv2 as new datagridview
dim dgv3 as new datagridview
dim dgv4 as new datagridview
sub processData()
conn = new sqlconnection(strcon)
conn1 = new sqlconnection(byconn)
conn.open
conn1.open
dim trans as sqltransaction = conn.begintransaction
dim trans1 as sqltransaction = conn1.begintransaction
try
dim con1 as new sqlconnection(strconn)
con1.open
dim cmd as new sqlcommand("some query",con1)
cmd.commandtype = commandtype.storedprocedure
dim da as new sqldataadapter(cmd)
dim dt as new datatable
da.fill(dt)
con1.close
dgv1.datasource = dt
for i as integer = 0 to dgv1.rowcount -1
getData2(i)
for j as integer = 0 to dgv2.rowcount -1
getData34()
end for
saveData1(i,conn,trans)
saveData2(conn1,trans1)
next
trans.commit
trans1.commit
conn.close
conn1.close
catch ex as exception
trans.rollback
trans1.rollback
conn.close
conn1.close
end try
end sub
sub getData2(i as integer)
dim con1 as new sqlconnection(strconn)
con1.open
dim cmd as new sqlcommand("some query",con1)
cmd.commandtype = commandtype.storedprocedure
cmd.parameters.addwithvalue("#PARAM",dgv1.item(0,i).value)
dim da as new sqldataadapter(cmd)
dim dt as new datatable
da.fill(dt)
con1.close
dgv2.datasource = dt
end sub
sub getdata34(i as integer)
dim con1 as new sqlconnection(strconn)
con1.open
dim cmd as new sqlcommand("some query",con1)
cmd.commandtype = commandtype.storedprocedure
cmd.parameters.addwithvalue("#PARAM",dgv2.item(0,i).value)
cmd.parameters.addwithvalue("#TYPE","LEFT")
dim da as new sqldataadapter(cmd)
dim dt as new datatable
da.fill(dt)
dgv3.datasource = dt
cmd =new sqlcommand("some query",con1)
cmd.commandtype = commandtype.storedprocedure
cmd.parameters.addwithvalue("#PARAM",dgv2.item(0,i).value)
cmd.parameters.addwithvalue("#TYPE","RIGHT")
da =new sqldataadapter(cmd)
dt =new datatable
da.fill(dt)
dgv4.datasource = dt
con1.close
end sub
sub saveData1(i as integer,cn as sqlconnection, trans as sqltransaction)
'some query with transaction
end sub
sub saveData2(cn as sqlconnection, trans as sqltransaction)
'some query with transaction
end sub
While processData called, in function getData2 and getData34 always give me timeout error message. adding timeout in sqlcommand not help me.
adding OPTION (RECOMPILE) in stored procedure also not help.
Perhaps, I miss something.

Related

"System.OutOfMemoryException: 'Out of memory.'" when reading image from SQL Server

I have images assigned to every button in my VB.NET form, the images come from SQL Server. The data type is varbinary(MAX).
This is my code:
Using con As New SqlConnection("con string")
Dim sql As String = "SELECT * FROM Inventory WHERE ID=#ID"
Using cmd As New SqlCommand(sql, con)
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = 3
con.Open()
Using myreader As SqlDataReader = cmd.ExecuteReader()
If myreader.Read() AndAlso Not DBNull.Value.Equals(myreader("Image")) Then
Boton3.Text = myreader("Item")
Boton3.Enabled = myreader("ONOFF")
Dim ImgSql() As Byte = DirectCast(myreader("Image"), Byte())
Using ms As New MemoryStream(ImgSql)
Boton3.BackgroundImage = Image.FromStream(ms)
con.Close()
End Using
Else
Boton3.Text = myreader("Item")
Boton3.BackgroundImage = Nothing
Boton3.Enabled = myreader("ONOFF")
End If
End Using
End Using
End Using
The platform is 64bit. I'm thinking it might have to do with not disposing properly, but I'm not sure since I'm new to coding.
EDIT SHOWING NEW CODE AND HOW I RETRIVE MORE THAN ONE RECORD:
Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
Dim dt As DataTable
Try
dt = GetInventoryDataByID(1)
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
If dt.Rows.Count > 0 Then
Boton1.Text = dt.Rows(0)("Articulo").ToString
Boton1.Enabled = CBool(dt.Rows(0)("ONOFF"))
If Not DBNull.Value.Equals(dt.Rows(0)("Imagen")) Then
Dim ImgSql() As Byte = DirectCast(dt.Rows(0)("Imagen"), Byte())
Using ms As New MemoryStream(ImgSql)
Boton1.BackgroundImage = Image.FromStream(ms)
End Using
Else
Boton1.BackgroundImage = Nothing
End If
Else
MessageBox.Show("No records returned")
End If
Dim dt2 As DataTable
Try
dt2 = GetInventoryDataByID(2)
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
If dt2.Rows.Count > 0 Then
Boton2.Text = dt2.Rows(0)("Articulo").ToString
Boton2.Enabled = CBool(dt2.Rows(0)("ONOFF"))
If Not DBNull.Value.Equals(dt2.Rows(0)("Imagen")) Then
Dim ImgSql() As Byte = DirectCast(dt2.Rows(0)("Imagen"), Byte())
Using ms As New MemoryStream(ImgSql)
Boton2.BackgroundImage = Image.FromStream(ms)
End Using
Else
Boton2.BackgroundImage = Nothing
End If
Else
MessageBox.Show("No records returned")
End If
End Sub
Private Function GetInventoryDataByID(id As Integer) As DataTable
Dim dt As New DataTable
Dim sql As String = "SELECT Imagen, Articulo, ONOFF FROM Inventario WHERE ID=#ID"
Using con As New SqlConnection("CON STRING"),
cmd As New SqlCommand(sql, con)
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = id
con.Open()
Using myreader As SqlDataReader = cmd.ExecuteReader()
dt.Load(myreader)
End Using
End Using
Return dt
End Function
End Class
You don't want to hold a connection open while you update the user interface. Separate you user interface code from your database code.
If you put a comma at the end of the first line of the outer Using block, both the command and the connection are included in same block. Saves a bit of indenting.
You are passing an integer to the #ID parameter but you have set the SqlDbType as a VarChar. Looks like a problem. I changed the SqlDbType to Int.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt As DataTable
Try
dt = GetInventoryDataByID(3)
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
If dt.Rows.Count > 0 Then
Boton3.Text = dt.Rows(0)("Item").ToString
Boton3.Enabled = CBool(dt.Rows(0)("ONOFF"))
If Not DBNull.Value.Equals(dt.Rows(0)("Image")) Then
Dim ImgSql() As Byte = DirectCast(dt.Rows(0)("Image"), Byte())
Using ms As New MemoryStream(ImgSql)
Boton3.BackgroundImage = Image.FromStream(ms)
End Using
Else
Boton3.BackgroundImage = Nothing
End If
Else
MessageBox.Show("No records returned")
End If
End Sub
Private Function GetInventoryDataByID(id As Integer) As DataTable
Dim dt As New DataTable
Dim sql As String = "SELECT * FROM Inventory WHERE ID=#ID"
Using con As New SqlConnection("con string"),
cmd As New SqlCommand(sql, con)
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = id
con.Open()
Using myreader As SqlDataReader = cmd.ExecuteReader()
dt.Load(myreader)
End Using
End Using
Return dt
End Function
EDIT Add Dispose on image
If Not DBNull.Value.Equals(dt.Rows(0)("Image")) Then
Dim ImgSql() As Byte = DirectCast(dt.Rows(0)("Image"), Byte())
Using ms As New MemoryStream(ImgSql)
If Boton3.BackgroundImage IsNot Nothing Then
Boton3.BackgroundImage.Dispose()
End If
Boton3.BackgroundImage = Image.FromStream(ms)
End Using
Else
If Boton3.BackgroundImage IsNot Nothing Then
Boton3.BackgroundImage.Dispose()
End If
End If
I resolved this issue by simply not using buttons. Instead I used pictureboxes as buttons and that resolved the issue. Im guesssing the problem is that buttons don't allow as much memory as pictureboxes.

Filling multi tables into dataset?

I have problem with my code which fills multi tables into my dataset. It loads all contents contained in tables of my database to only one table in dataset. My code is shown below. How to load those tables from database into a dataset , that has the same number of tables and contents.
Private Sub Filldataset()
Private cnn As OleDbConnection
Private dt As New DataTable
Private da As New OleDbDataAdapter
Private cmd As New OleDbCommand
Private ds As New DataSet
Dim tblrestrictions As String() = New String() {Nothing, Nothing, Nothing, "TABLE"}
Dim userTables As DataTable = Nothing
userTables = cnn.GetSchema("Tables", tblrestrictions)
Dim i As Integer
For i = 1 To userTables.Rows.Count - 1 Step 1
cnn = New OleDbConnection(Str)
cnn.Open()
cmd = cnn.CreateCommand
cmd.CommandText = "select * from" & " " & userTables.Rows(i)(2).ToString
dt.Clear()
da.SelectCommand = cmd
da.Fill(dt)
da.Fill(ds)
Next
cnn.Close()
MessageBox.Show(ds.Tables.Count)
End Sub
Connections can be created elsewhere but should not be opened or closed until directly before an directly after you use them. You will have to adjust this code for an Oledb application.
Private Sub GetData()
cn.Open()
Dim dt As DataTable = cn.GetSchema("Tables")
cn.Close()
Dim ds As New DataSet
Dim row As DataRow
For Each row In dt.Rows
Dim strTableName As String = row(2).ToString
Dim strSQL As String = "Select * From " & strTableName
Dim cmd As New SqlCommand(strSQL, cn)
Dim da As New SqlDataAdapter
da.SelectCommand = cmd
da.Fill(ds, strTableName)
Next
Debug.Print(ds.Tables.Count.ToString)
End Sub
I scoped several variables locally that you will want to scope to the class like the dataset

Refreshing Data - Stored procedure

I need help to made auto-refresh for my stored procedure and fill datatable with new informations. I need suggestions, I tried to use Timer who clear datatable and execute stored procedure again, but I think that's bad solution.
My current code:
Public Sub Efficiency_Procedure()
_eff.Clear()
Dim dtStart As String
dtStart = FormatDateTime(DateTime.Today)
Dim cmd As New SqlCommand("spEfficiencyConfB", MyConnection)
Dim outParam As SqlParameter
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#startTime", SqlDbType.DateTime).Value = dtStart
cmd.Parameters.Add("#stopTime", SqlDbType.DateTime).Value = dtStart
outParam = cmd.Parameters.Add("#nrOut", SqlDbType.Int)
outParam.Direction = ParameterDirection.Output
If MyConnection.State = ConnectionState.Closed Then
MyConnection.Open()
End If
Dim dr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)
_eff.Load(dr)
dr.Close()
cmd.Dispose()
If MyConnection.State = ConnectionState.Open Then
MyConnection.Close()
End If
End Sub
Thank you

Populate Combobox from SQL Server vb.net

I'm trying to populate a combobox with data from SQL Server. This is my code so far. There are asterisks around the errors. Also, ignore the comments.
Private Sub frmOriginal_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim connetionString As String = Nothing
Dim sqlcon As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter()
Dim ds As New DataSet()
Dim i As Integer = 0
Dim sql As String = Nothing
connetionString = "Data Source = RENEE\SQLEXPRESS;Initial Catalog=Stocks;Integrated Security = True"
sql = "select * from TickerSymbol"
sqlcon = New SqlConnection(connetionString)
Try
sqlcon.Open()
command = New SqlCommand(sql, sqlcon)
adapter.SelectCommand = command
adapter.Fill(ds)
adapter.Dispose()
command.Dispose()
sqlcon.Close()
cboID.DataSource = ds.Tables(0)
cboID.ValueMember = "TickerSymbol"
cboID.DisplayMember = "TickerSymbol"
Catch ex As Exception
'MessageBox.Show("Can not open connection ! ")'
End Try
End Sub
Private Sub cboID_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboID.SelectedIndexChanged
Dim dr As SqlDataReader
Dim command As New SqlCommand *(queryString, connection)*
Dim dataReader As SqlDataReader = command.ExecuteReader()
Dim sqlcon As SqlConnection
Dim cmd As SqlCommand
sqlcon = New SqlConnection
sqlcon.ConnectionString = "Data Source = RENEE\SQLEXPRESS;Initial Catalog=Stocks;Integrated Security = True"
Try
sqlcon.Open()
cmd = New SqlCommand
cmd.CommandText = " select * from TickerSymbol where TickerSymbol = '" & cboID.Text & "'"
cmd = New SqlCommand(cmd.CommandText, sqlcon)
dr = cmd.ExecuteReader
While dr.Read()
'TxtID.Text = dr.GetInt32(0)'
'TxtSN.Text = dr.GetString(1)'
'TxtGender.Text = dr.GetString(2)'
'TxtPhone.Text = dr.GetInt32(3)'
'TxtAdrress.Text = dr.GetString(4)'
lblCompanyName.Text = dataReader.GetString(1)
lblPurchasePrice.Text = dataReader.GetSqlMoney(2)
lblQtyPurchased.Text = dataReader.GetInt32(3)
lblPurchaseDate.Text = dataReader.GetDateTime(4)
End While
sqlcon.Close()
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
sqlcon.Dispose()
End Sub
Please use parameterized queries as this will format values properly e.g. apostrophes in text will escape properly with parameters while without you must handle them, dates will be formatted properly too. Code is much cleaner also.
Example, syntax for Framework 3.5 and higher. If a connection string is used more than once then consider placing it in a private variable or under My.Settings under project properties.
Using cn As New SqlConnection With {.ConnectionString = "Data Source = RENEE\SQLEXPRESS;Initial Catalog=Stocks;Integrated Security = True"}
Using cmd As New SqlCommand With {.Connection = cn, .CommandText = "select * from TickerSymbol where TickerSymbol = #TickerSymbol"}
cmd.Parameters.AddWithValue("#TickerSymbol", cboID.Text)
cn.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read
'
'
'
End While
End If
End Using
End Using

delete selected row from gridview and and update databse in vb.net windows form

I have a Delete button and i am trying to delete selected rows from gridview and database by clicking on that button. but having following code i am getting error like Argument out of range and convert to int.
Private Sub dltButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dltButton.Click
'Dim StudentId As String
'StudentId =
'con.Open()
'cmd.CommandText = "delete from KaiyumVbStudent where StudentID = '"&StudentId&"'"
'cmd.Connection = con
Dim i As Integer = DataGridView1.SelectedRows(0).Index
DataGridView1.Rows.Remove(DataGridView1.SelectedRows(0))
con = New SqlConnection(constring)
con.Open()
Me.StudentID = Convert.ToInt32(DataGridView1.SelectedRows(0).Index)
cmd = New SqlCommand("Delete from KaiyumVbStudent where StudentID = '#StudentID'", con)
cmd.ExecuteNonQuery()
Call databind()
Private Sub databind()
con = New SqlConnection(constring)
con.Open()
cmd = New SqlCommand("Select *from KaiyumVbStudent", con)
Dim dr As SqlDataReader = cmd.ExecuteReader()
dt = New DataTable()
dt.Load(dr)
Me.DataGridView1.DataSource = dt
End Sub
First put our code in try catch statement and check student Id datatype
Your are missing one statement
cmd.Parameters.AddWithValue("#StudentID", StudentID);
I hope you it is work..

Resources