I'm updating SQL Server from VB.NET and keep getting the 'Query Timeout Error', I have lot's of sub routines that I run in sequence that look like the following:
Public Shared Sub Update_DailyRatings()
Dim stallStats As String = ""
Dim win As Integer = 0
Dim mSplit As Array
Dim cn As OleDbConnection = New OleDbConnection(MainForm.connectStringPublic)
cn.Open()
Dim selectString As String = "Select * FROM DailyRatings"
Dim cmd As OleDbCommand = New OleDbCommand(selectString, cn)
Dim reader As OleDbDataReader = cmd.ExecuteReader()
While (reader.Read())
stallStats = Get_Stall_Stats(reader("Track").ToString, CInt(reader("Stall")), CDbl(reader("Distance")))
If stallStats = "" Then
MainForm.NonQuery("UPDATE DailyRatings SET StallWin = 999 WHERE Horse = '" & reader("Horse").ToString & "'")
Else
mSplit = Split(stallStats, ",")
win = mSplit(0)
MainForm.NonQuery("UPDATE DailyRatings SET StallWin = " & win & " WHERE Horse = '" & reader("Horse").ToString & "'")
End If
End While
reader.Close()
cn.Close()
End Sub
The NonQuery sub looks like this:
Public Sub NonQuery(ByVal SQL As String)
Dim query As String = SQL
Try
Dim cn3 As OleDbConnection = New OleDbConnection(connectStringPublic)
cn3.Open()
Dim cmd As OleDbCommand = New OleDbCommand(query, cn3)
cmd.CommandTimeout = 90
cmd.ExecuteNonQuery()
cn3.Close()
cn3.Dispose()
cmd.Dispose()
OleDbConnection.ReleaseObjectPool()
Catch e As System.Exception
Clipboard.SetText(query)
MsgBox(e.Message)
Finally
End Try
End Sub
As you can see I've been trying ideas to fix this that I found in other threads such as extending the timeout and using the Dispose() and ReleaseObjectPool() methods but it hasn't worked, I still get query timeout error at least once when running all my subs in sequence, it's not always the same sub either.
I recently migrated from Access, this never used to happen with Access.
If you are dealing with Sql Server why are you using OleDb? I guessed that is was really access.
While your DataReader is open, your connection remains open. With the amount of processing you have going on, it is no wonder that your connection is timing out.
To begin, connections and several other database objects need to be not only closed but disposed. They may contain unmanaged resources which are released in the .Dispose method. If you are using an object that exposes a .Dispose method use Using...End Using blocks. This will take care of this problem even if there is an error.
Actually you have 2 distinct operations going on. First you are retrieving DailyRatings and then you are updating DailyRatings base on the data retrieved. So we fill a Datatable with the first chunk of data and pass it off to the second operation. Our first connection is closed and disposed.
In operation 2 we create our connection and command objects just as before except now our command has parameters. The pattern of the command is identical for every .Execute, only the values of the parameters change. This pattern allows the database, at least in Sql Sever, to cache a plan for the query and improve performance.
Public Shared Function GetDailyRatings() As DataTable
Dim dt As New DataTable
Using cn As New OleDbConnection(MainForm.connectStringPublic),
cmd As New OleDbCommand("Select * FROM DailyRatings", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
Public Sub UpdateDailyRatings()
Dim dt = GetDailyRatings()
Using cn As New OleDbConnection(connectStringPublic),
cmd As New OleDbCommand("UPDATE DailyRatings SET StallWin = #Stall WHERE Horse = #Horse")
cmd.Parameters.Add("#Stall", OleDbType.Integer)
cmd.Parameters.Add("#Horse", OleDbType.VarChar)
cn.Open()
For Each row As DataRow In dt.Rows
cmd.Parameters("#Horse").Value = row("Horse").ToString
Dim stallStats As String = Get_Stall_Stats(row("Track").ToString, CInt(row("Stall")), CDbl(row("Distance")))
If stallStats = "" Then
cmd.Parameters("#Stall").Value = 999
Else
cmd.Parameters("#Stall").Value = CInt(stallStats.Split(","c)(0))
End If
cmd.ExecuteNonQuery()
Next
End Using
End Sub
Private Function GetStallStats(Track As String, Stall As Integer, Distance As Double) As String
Dim s As String
'Your code here
Return s
End Function
Note: OleDb does not pay attention to parameters names. It is the order that they appear in the query statement must match the order that they are added to the Parameters collection.
It's possible that OleDbDataReader is locking your table or connection as it get the data with busy connection. You can store the data in a DataTable by using OleDbDataAdapter and loop through it to run your updates. Below is the snippet how your code would look like:
Dim cmd As OleDbCommand = New OleDbCommand(selectString, cn)
Dim adapter As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim dt As New DataTable()
adapter.Fill(dt)
For Each reader As DataRow In dt.Rows
stallStats = Get_Stall_Stats(reader("Track").ToString, CInt(reader("Stall")), CDbl(reader("Distance")))
If stallStats = "" Then
MainForm.NonQuery("UPDATE DailyRatings SET StallWin = 999 WHERE Horse = '" & reader("Horse").ToString & "'")
Else
mSplit = Split(stallStats, ",")
win = mSplit(0)
MainForm.NonQuery("UPDATE DailyRatings SET StallWin = " & win & " WHERE Horse = '" & reader("Horse").ToString & "'")
End If
Next
cn.Close()
Related
I get this error when I run the code. The records are inserted into the table, but the program stops at the error.
The parameterized query '(#EmpName varchar(8000),#USDBasic varchar(8000),#OtherUSDEarning' expects the parameter '#EmpName', which was not supplied.
Code:
Dim connetionString As String
Dim cnn As SqlConnection
connetionString = "Data Source=Server\SQlExpress;Initial Catalog=CreSolDemo;User ID=sa;Password=Mkwn#011255"
cnn = New SqlConnection(connetionString)
If DataGridView1.Rows.Count > 0 Then
Dim cmd As New Data.SqlClient.SqlCommand
cmd.CommandText = " INSERT INTO TempPeriodTrans (EmpName, USDBasic, OtherUSDEarnings, ZDollarBasic, OtherZDEarnings) VALUES (#EmpName, #USDBasic, #otherUSDEarnings, #ZDollarBasic, #OtherZDEarnings) "
cmd.Parameters.Add("#EmpName", SqlDbType.VarChar)
cmd.Parameters.Add("#USDBasic", SqlDbType.VarChar)
cmd.Parameters.Add("#OtherUSDEarnings", SqlDbType.VarChar)
cmd.Parameters.Add("#ZDollarBasic", SqlDbType.VarChar)
cmd.Parameters.Add("#OtherZDEarnings", SqlDbType.VarChar)
cmd.Connection = cnn
cnn.Open()
For i As Integer = 0 To DataGridView1.Rows.Count - 1
cmd.Parameters(0).Value = DataGridView1.Rows(i).Cells(0).Value
cmd.Parameters(1).Value = DataGridView1.Rows(i).Cells(1).Value
cmd.Parameters(2).Value = DataGridView1.Rows(i).Cells(2).Value
cmd.Parameters(3).Value = DataGridView1.Rows(i).Cells(3).Value
cmd.Parameters(4).Value = DataGridView1.Rows(i).Cells(4).Value
cmd.ExecuteNonQuery()
Next
cnn.Close()
End If
MsgBox("Record saved")
End Sub
There seem to be a few things here.
As a rule, any time you open a connection to your data base it should be wrapped in a Using block so that that connection gets closed and disposed before you exit that block
You have a lot of params that are being set as SqlDbType.varchar where you should probably have other types. (SqlDbType.Money in particular)
When you are working with sqlcommand, it is worth wrapping it in a using block as well and creating a new one as you need it.
There is some memory to it where it will try not to reuse parameters in subsequent queries. Instead of just changing the value of the param, throw that sqlCommand in the trash bin each time and grab a new one. This is where I believe your problem is. I moved the sqlcommand creation into your loop and declare the values in-line below.
Also, protip, avoid including your actual password in the connetion string on Stack Overflow
Dim connectionString As String = "yourConnectionString"
Using cnn As new SqlConnection(connectionString)
cnn.Open()
For Each row in DataGridView1.Rows
Using cmd As New Data.SqlClient.SqlCommand("INSERT INTO TempPeriodTrans (EmpName, USDBasic, OtherUSDEarnings, ZDollarBasic, OtherZDEarnings) Values (#EmpName, #USDBasic, #otherUSDEarnings, #ZDollarBasic, #OtherZDEarnings) ", cnn)
cmd.Parameters.Add("#EmpName", SqlDbType.VarChar).value = row.Cells(0).Value
cmd.Parameters.Add("#USDBasic", SqlDbType.VarChar).value = row.Cells(1).Value
cmd.Parameters.Add("#OtherUSDEarnings", SqlDbType.VarChar).value = row.Cells(2).Value
cmd.Parameters.Add("#ZDollarBasic", SqlDbType.VarChar).value = row.Cells(3).Value
cmd.Parameters.Add("#OtherZDEarnings", SqlDbType.VarChar).value = row.Cells(4).Value
cmd.ExecuteNonQuery()
End using
Next
End using
MsgBox("Record Saved")
End Sub
I'm currently working on my project for which I used VB.NET 2019 and SQL server. I need to create a function which auto generates IDs.
I want my IDs to be like these: P001, P002, P003 etc. Can someone show me how to code it? Below is my code
Private Sub Form4_Load_1(sender As Object, e As EventArgs) Handles MyBase.Load
BindData()
Dim data As String = "Data Source=LAPTOP-M8KKSG0I;Initial Catalog=Oceania;Integrated Security=True"
Dim con As New SqlConnection(data)
Try
If Con.State = ConnectionState.Closed Then
con.Open()
End If
Dim sql As String = "Select Max(PatientID) from Patient"
Dim cmd As New SqlCommand(sql, con)
Dim Max As String = cmd.ExecuteScalar
If Max > 0 Then
TextBox1.Text = Max + 1
Else
TextBox1.Text = "P01"
End If
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
You can try like this. Here 1 is an auto-generated number that may be an identity key column value from a table in SQL Server.
Dim number As Integer = 1
Dim numberText As String = "P" & number.ToString().PadLeft(3, "0")
Live demo
You can add a computed column like this in your table for auto-generating the sequences. This will reduce the chances of duplicate value runtime once more than one person will do the entry simultaneously.
Alter table Patient ADD PatientCode AS ('P' + Convert(Varchar(3),CONCAT(REPLICATE('0', 3 - LEN(PatientID)), PatientID)) )
To get the column value dynamically you can try the below code to generate function.
Private Sub GenerateSequnce()
Dim constring As String = "Data Source=TestServer;Initial Catalog=TestDB;User id = TestUser;password=test#123"
Using con As New SqlConnection(constring)
Using cmd As New SqlCommand("Select Top 1 ISNULL(TaxCode, 0) from Tax_Mst Order By TaxCode Desc", con)
cmd.CommandType = CommandType.Text
Using sda As New SqlDataAdapter(cmd)
Using dt As New DataTable()
sda.Fill(dt)
Dim maxNumberCode = dt.Rows(0)("TaxCode").ToString()
If (maxNumberCode = "0") Then
maxNumberCode = "1"
End If
Dim numberText As String = "P" & maxNumberCode.ToString().PadLeft(3, "0")
End Using
End Using
End Using
End Using
End Sub
Here the column TaxCode is int with identity constraint.
With the minor correction in your code, you can achieve this as shown below.
Dim data As String = "Data Source=LAPTOP-M8KKSG0I;Initial Catalog=Oceania;Integrated Security=True"
Dim con As New SqlConnection(data)
Try
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim sql As String = "Select ISNULL(Max(PatientID), 0) from Patient"
Dim cmd As New SqlCommand(sql, con)
Dim Max As String = cmd.ExecuteScalar
If (Max = "0") Then
Max = "1"
Else
Max = CInt(Max) + 1
End If
Dim numberText As String = "P" & Max.ToString().PadLeft(3, "0")
TextBox1.Text = numberText
Catch ex As Exception
MsgBox(Err.Description)
End Try
OUTPUT
enter image description hereI am using a SQL Server Compact 3.5 database file (.sdf) in vb.net
There was an error parsing the query. [Token line number,Token line offset,,Token in error,,]
Dim flag As Boolean
Dim flag2 As Boolean
Me.OpenFileDialog1.Filter = "mdb files (*.mdb)|"
Me.OpenFileDialog1.Filter = "mdb files (*.mdb)|*.mdb|All files (*.*)|*.*"
flag2 = (Me.OpenFileDialog1.ShowDialog() = DialogResult.OK)
If flag2 Then
flag = (Operators.CompareString(FileSystem.Dir(Me.OpenFileDialog1.FileName, FileAttribute.Normal), "", False) <> 0)
End If
Dim myConnectionStringMDB As String = "provider=Microsoft.Ace.OLEDB.12.0;" & "data source=" & Me.OpenFileDialog1.FileName
Dim myConnectionStringSQL As String = "Provider=Microsoft.SQLSERVER.CE.OLEDB.3.5;" & "Data Source=" & Application.StartupPath & "\Archive.sdf"
Using conSQL As OleDbConnection = New OleDbConnection(), conMDB As OleDbConnection = New OleDbConnection()
conSQL.ConnectionString = myConnectionStringSQL
conSQL.Open()
conMDB.ConnectionString = myConnectionStringMDB
conMDB.Open()
Using cmdSQL As OleDbCommand = New OleDbCommand(), cmdMDB As OleDbCommand = New OleDbCommand()
cmdMDB.CommandType = Data.CommandType.Text
cmdMDB.Connection = conMDB
cmdMDB.CommandText = "SELECT * FROM [student]"
Dim daMDB = New System.Data.OleDb.OleDbDataAdapter(cmdMDB)
Dim dt = New Data.DataTable()
daMDB.Fill(dt)
For Each dr As Data.DataRow In dt.Rows
' change row status from "Unchanged" to "Added" so .Update below will insert them
dr.SetAdded()
Next
cmdSQL.CommandType = Data.CommandType.Text
cmdSQL.Connection = conSQL
cmdSQL.CommandText = "SELECT * FROM [student]"
Dim daSQL = New System.Data.OleDb.OleDbDataAdapter(cmdSQL)
Dim cbuilderMDB = New OleDbCommandBuilder(daSQL)
cbuilderMDB.QuotePrefix = "["
cbuilderMDB.QuoteSuffix = "]"
daSQL.Update(dt)
End Using
conSQL.Close()
conMDB.Close()
End Using
I got rid of the extra boolean variables flag and flag2 and just tested the values directly.
I divided the Using blocks into 2 blocks so the first group of objects can be closed and disposed before the next group starts their work.
I shortened the code by passing properties directly to the constructors of the objects where possible. DataAdapter and StringBuilder also expose a .Dispose method so I included them in the Using blocks.
daMDB.AcceptChangesDuringFill = False
This line of code allows the .DataRowState to remain as Added (normally it is changed to Unchanged by the .Fill method) so, the DataTable will be ready to add all the records to the second table without the loop.
I don't believe that student is a reserved word in either database so I removed the square brackets.
Both the .Fill and the .Update methods of the DataAdapter will .Open and .Close the connection if they find the connection closed. If they find it open they will leave it open. So, closing the connection is not necessary. Also the End Using closes and disposes all objects included in the Using portion (first line including commas) of the block.
Private Sub OPCode()
OpenFileDialog1.Filter = "mdb files (*.mdb)|*.mdb|All files (*.*)|*.*"
Dim MDBFile As String
If OpenFileDialog1.ShowDialog = DialogResult.OK AndAlso Not String.IsNullOrEmpty(OpenFileDialog1.FileName) Then
MDBFile = OpenFileDialog1.FileName
Else
Exit Sub
End If
Dim myConnectionStringMDB As String = "provider=Microsoft.Ace.OLEDB.12.0;" & "data source=" & MDBFile
Dim myConnectionStringSQL As String = "Provider=Microsoft.SQLSERVER.CE.OLEDB.3.5;" & "Data Source=" & Application.StartupPath & "\Archive.sdf"
Dim dt = New Data.DataTable()
Using conMDB As OleDbConnection = New OleDbConnection(myConnectionStringMDB),
cmdMDB As OleDbCommand = New OleDbCommand("SELECT * FROM student", conMDB),
daMDB As New System.Data.OleDb.OleDbDataAdapter(cmdMDB)
daMDB.AcceptChangesDuringFill = False
daMDB.Fill(dt)
End Using
Using conSQL As OleDbConnection = New OleDbConnection(myConnectionStringSQL),
cmdSQL As OleDbCommand = New OleDbCommand("SELECT * FROM student", conSQL),
daSql As New OleDbDataAdapter(cmdSQL),
cbuilderMDB As New OleDbCommandBuilder(daSql)
daSql.Update(dt)
End Using
End Sub
I am not professional but i am trying to learn VB.net. I am making a project where i am stuck where i want to get each unique value from a column in access database and add it to my combobox. Can anybody help me ??
Private Sub showItems()
Dim comm As OleDbCommand
Dim commStr As String = "SELECT Item_Name FROM Add_Items WHERE (Item_Name <> '"
Dim RD As OleDbDataReader
conn = New OleDbConnection(connStr)
conn.Open()
If cbItemname.Items.Count = 0 Then
comm = New OleDbCommand("Select Item_Name from Add_Items", conn)
RD = comm.ExecuteReader
While RD.Read
cbItemname.Items.Add(RD.GetString(0))
End While
End If
For Each i As Object In cbItemname.Items
comm = New OleDbCommand(commStr & i & "')", conn)
RD = comm.ExecuteReader
While RD.Read
cbItemname.Items.Add(RD.GetString(0))
Exit While
End While
Next
conn.Close()
End Sub
comm = New OleDbCommand("Select DISTINCT Item_Name from Add_Items", conn)
http://office.microsoft.com/en-in/access-help/HV080760568.aspx
You can get this error because your database table name is incorrect. Make sure you are in the Tables tab and check the name of the table. DISTINCT and UNIQUE(for MySQL) is correct solution for this.
I followed instructions given by vipul. It was working nicely and i made some more private subs for brands and Models and it suddenly stopped working. Now, when my form loads from previous parent form it hangs.
Private Sub showItems()
Dim comm As OleDbCommand
Dim commStr As String = "SELECT DISTINCT Item_Name from Add_Items"
Dim ReadData As OleDbDataReader
itemnamecombo.Items.Clear()
ItemChkboxList.Items.Clear()
Try
conn = New OleDbConnection(ConnStr)
conn.Open()
comm = New OleDbCommand(commStr, conn)
ReadData = comm.ExecuteReader
While ReadData.Read
itemnamecombo.Items.Add(ReadData.GetString(0))
ItemChkboxList.Items.Add(ReadData.GetString(0))
End While
Catch ex As Exception
'MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
If itemnamecombo.Items.Count <> 0 Then
itemnamecombo.SelectedIndex = 0
End If
End Sub
Is there a way to use DateTimePicker as your searching device for ListView?
I don't know how to use DateTimePicker as my search engine...
HERE IS THE CODES FOR MY SEARCH:
Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim da As SqlDataAdapter
Dim ds As DataSet
Dim itemcoll(100) As String
Me.ListView1.View = View.Details
Me.ListView1.GridLines = True
ListView1.Items.Clear()
conn = New SqlConnection("Data Source=#####;Initial Catalog=#####;Persist Security Info=True;User ID=#####;Password=#####")
Dim strQ As String = String.Empty
strQ = "SELECT ControlNo,EmpNo,CheckOutDate,CheckOutTime,TaxiNo,PlateNo,Model,Make FROM dbo.ChkInOut WHERE ControlNo ='" + txtsearch.Text + "'"
cmd = New SqlCommand(strQ, conn)
da = New SqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "Table")
Dim i As Integer = 0
Dim j As Integer = 0
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
itemcoll(j) = ds.Tables(0).Rows(i)(j).ToString()
Next
Dim lvi As New ListViewItem(itemcoll)
Me.ListView1.Items.Add(lvi)
Next
There are few problems with your code as is, so let's take them one at a time
SqlCommand inherits from DbCommand, which implements the IDisposable interface.
The primary use of this interface is to release unmanaged resources.
The best way do that is with the Using keyword. For a code example of that, take a look at the sample code at the bottom of this page.
Same goes for SqlConnection, wrap it in a Using statement.
Don't concatenate strings together to make SQL queries, this opens your application up to SQL Injection attacks. There are examples of how to create parameterized queries here and here (unfortunately I didn't see a good example on MSDN).
In your case, the query will look like this:
strQ = "SELECT ControlNo, ..<rest of columns>.. ,Model,Make " & _
"FROM dbo.ChkInOut " & _
"WHERE ControlNo = #controlNo"
cmd = New SqlCommand(strQ, conn)
cmd.Parameters.AddWidthValue("#controlNo", txtsearch.Text);
... rest of code here ...
To query by a user specified date, you need to first get the date from the DateTimePicker.Value property. Then construct a query (like in the example above) and pass a parameter with the selected date. You may find this question abou SQL Server dates helpful.