Getting Timeout expire error using data reader - sql

Using VB.Net and SQL
Code
myConnection = New SqlConnection(Connection)
myConnection.Open()
Dim myCommand As SqlCommand = New SqlCommand("proc_g_report", myConnection)
Dim myReader As SqlDataReader = myCommand.ExecuteReader()
DTResults.Load(myReader)
Throwing error as "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding"
Error on this line Dim myReader As SqlDataReader = myCommand.ExecuteReader()
And I cannot change the database pool size due to security reason, Please any one advise.

Try Setting CommandTimeout
myConnection = New SqlConnection(Connection)
myConnection.Open()
Dim myCommand As SqlCommand = New SqlCommand("proc_g_report", myConnection)
myCommand.CommandTimeout=0
Dim myReader As SqlDataReader = myCommand.ExecuteReader()
DTResults.Load(myReader)

The error seems to be unrelated but, if you want to call the execution of a stored procedure you need to tell what is the CommandType passed.
The default is CommandType = CommandType.Text, so your command text (proc_g_report) is treated as if it was a SELECT/INSERT or other standard T-SQL statement.
You need to set the CommandType and possibly add the Using Statement around the disposable objects....
Using myConnection = New SqlConnection(Connection)
Using myCommand = New SqlCommand("proc_g_report", myConnection)
myCommand.CommandType = CommandType.StoredProcedure
myConnection.Open()
Using myReader = myCommand.ExecuteReader()
DTResults.Load(myReader)
End Using
End Using
End Using
Of course you could easily test if this is the problem using the Sql Server Management Studio and call that stored procedure from you working PC and check what amount of time is required to complete. If the time is less than 30 seconds (the default timeout for the SqlCommand execution) then the problem is elsewhere and not in the Timeout value.

Related

What would cause my dataset to drop a row?

I have a SQL statement that, when ran in SSMS, returns 6 rows. After attaching the statement to the command text of a VB.NET SQLCommand with a command type of Text, reading it with a SqlDataReader, and attaching it to a dataset, the returned dataset only has 5 rows.
At first, I assumed it was an issue with the data. However, after several bouts of removing and adding rows to the source table with varying data, it was obvious that I was always getting the total row count - 1. I then decided to just use a SQLDataAdapter to populate the DataSet and the proper number of rows was returned.
Dim ds As New DataSet
Dim sqlCmd as New SqlCommand
Dim sqlCn As New SqlConnection
Dim sqlR As New SqlCommand
sqlCn.ConnectionString = "SomeConnectionString"
With sqlCmd.CommandText = "Select * from DummyTable"
.CommandType = CommandType.Text
.Connection = sqlCn
End With
sqlCn.Open()
sqlR = sqlCmd.ExecuteReader
sqlR.Read()
If sqlR.HasRows() Then
ds.Tables.Add("DummyTable")
ds.Tables(0).Load(sqlR)
return ds
End If
From here, I'm expecting to see the 6 rows from DummyTable. Instead, I'm seeing only 5.
However, if I use the following:
Dim da as SqlDataAdapter
Using sqlCn
da.SelectCommand = New SqlCommand(sqlCmd.CommandText, sqlCn)
da.Fill(ds)
End Using
Return ds
I get the full 6 rows. Is there something I'm missing about the way a DataSet's Tables.Add(tableName) or Tables(n).Load(dataReader) works? I had never worked with SqlDataReaders prior to this and was told to stick with them as our other projects use them.
Your code is already reading the first line of the query with the line sqlR.Read(). This line is unnecessary in your code. Remove it and it will work fine.
Also SqlCommand, SqlConnection and SqlDataReader implement iDisposable, so be sure to use using-statement with them:
Using sqlCn As New SqlConnection("SomeConnectionString")
sqlCn.Open()
Using sqlCmd as New SqlCommand
With sqlCmd.CommandText = "Select * from DummyTable"
.CommandType = CommandType.Text
.Connection = sqlCn
End With
Using sqlR As SqlDataReader = sqlCmd.ExecuteReader
If sqlR.HasRows() Then
Dim ds As New DataSet
ds.Tables.Add("DummyTable")
ds.Tables(0).Load(sqlR)
return ds
End If
End Using
End Using
End Using

Wait until SQL Server Agent Job finishes

I am running a query to execute/start a SQL Server Agent Job which takes sometimes 4 to 5 hours to finish. I would like to wait until that job finishes and then continue with the program/code.
Here is my query I am running to start the stored procedure:
Dim connectionString As String = "HIDDEN"
Dim con As SqlConnection = New SqlConnection(connectionString)
con.Open()
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = con
cmd.CommandText = "USE msdb; EXEC dbo.sp_start_job N'FWP FULL Daily'"
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
con.Close()
// -- WAIT UNTIL STORED PROCEDURE FINISHES --
//Continue Code From Here on..........
How would I do this??
Thank you.

vb.net sql parameterization

I really need help this time. I search everywhere, tried numerous solutions. but i can't seem to solve my problem. Now i'm going to ask, please help. I have been having this problem for a week now.
ExecuteSQL("select * from account_database where idnum= #idnum and password= #pass")
'Dim idnum As New SqlParameter("#idnum", SqlDbType.VarChar)
'Dim pass As New SqlParameter("#pass", SqlDbType.VarChar, -1)
'idnum.Value = idnumtxt.Text
'pass.Value = output
'cmd.Parameters.Add(idnum)
'cmd.Parameters.Add(pass)
cmd.Parameters.Add("#idnum", SqlDbType.VarChar).Value = idnumtxt.Text
cmd.Parameters.Add("#pass", SqlDbType.VarChar, -1, "password").Value = output
those commented out lines are the codes which i have tried, also there are codes which i implemented that also failed.
The error message concludes as "Must declare scalar variable #idnum"
i really need help please. Please shine some light.
This is the code what the function executeSQL contains :
Public Shared Sub ExecuteSQL(ByVal strSQL As String)
Try
If connection.State = 1 Then ' check connection if open
connection.Close()
End If
' connection
connection.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Jr\documents\visual studio 2010\Projects\VotingSystem\VotingSystem\Resources\Database.mdf;Integrated Security=True;User Instance=True"
connection.Open()
Dim rowAffected As Integer = 0
'cmd = New SqlCommand(strSQL, connection) 'buiding the sql command with the use of strSQL (sql statement) and connection (database connection)
cmd = New SqlCommand(strSQL, connection)
DARec = New SqlDataAdapter(strSQL, connection) 'buiding the adapter
cb = New SqlCommandBuilder(DARec)
rowAffected = cmd.ExecuteNonQuery() 'executing of sql statement
successID = 1
connection.Close()
Catch ex As Exception
successID = 0
MsgBox(ex.Message)
End Try
End Sub
Thanks and please help.
Problem is simply you're doing this in the wrong order. You're attempting to execute your SQL statement before defining the parameters. You don't need ExecuteSQL() until you've defined your parameters. It likely breaks on the following line in ExecuteSQL()
' See how many rows the query will impact
' Since #idnum and #pass are not defined until the
' ExecuteSQL() sub is finished, this line breaks.
rowAffected = cmd.ExecuteNonQuery()
You need to build your SqlCommand() to first include the select statement, and then use AddWithValue() on the parameters you've defined in the string. Defining the datatypes is also unnecessary because your database already knows, and form validation should handle input.
' Define your connection
connection.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Jr\documents\visual studio 2010\Projects\VotingSystem\VotingSystem\Resources\Database.mdf;Integrated Security=True;User Instance=True"
' Setup your SQL Command.
cmd = New SqlCommand("select * from account_database where idnum = #idnum and password = #pass", connection)
' Define the parameters you've created
cmd.Parameters.AddWithValue("#idnum", idnumtxt.Text)
cmd.Parameters.AddWithValue("#pass", output)
' Now execute your statement
connection.open()
cmd.ExecuteNonQuery()
connection.close()
And here is a better version of the above code, since you understand the order of events now. This ensures that in the event of exception the connection is closed.
strConn = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Jr\documents\visual studio 2010\Projects\VotingSystem\VotingSystem\Resources\Database.mdf;Integrated Security=True;User Instance=True"
strSQL = "select * from account_database where idnum = #idnum and password = #pass"
Using connection As New SqlConnection(strConn), cmd As SqlCommand(strSQL, connection)
cmd.Parameters.Add("#idnum", SqlDbType.VarChar).Value = idnumtxt.Text
cmd.Parameters.Add("#pass", SqlDbType.VarChar, -1, "password").Value = output
connection.Open()
cmd.ExecuteNonQuery()
End Using
Try this:
cmd.Parameters.AddWithValue("idnum", idnumtxt.Text)
Reference:
SqlParameterCollection.AddWithValue # MSDN.
It should just be a case of the following to add an input param
cmd.Parameters.Add("#idnum", idnumtxt.Text)
Except you'll need cmd.parameters.add() before the executesql as you're currently defining your params after executesql has ran.

VB.NET - Multiple SQLDataReader's

I develop a lot in ASP.NET and I know that you can only open one SQLDataReader for each SQLConnection. However, this does not appear to be the case in VB.NET (form application) i.e. I have opened multiple SQLDataReaders for one connection object. Is this allowed in VB.NET?
If there is not an obvious answer to this then I will post some code.
Here is some code:
Public Function CheckActiveReviews()
Dim objCon As SqlConnection
Dim objCommand As SqlCommand, objCommand2 As SqlCommand
Dim objDR As SqlDataReader, objDR2 As SqlDataReader
Try
objCon = New SqlConnection("Data Source=TestDatabase;Initial Catalog=TestTable;User ID=TestUser;Password=TestPassword;MultipleActiveResultSets=True")
objCommand = New SqlCommand
objCommand.Connection = objCon
objCommand2 = New SqlCommand
objCommand2.Connection = objCon
objCon.Open()
objCommand.CommandText = "SELECT ID FROM Person WHERE PersonID > 1000"
objDR = objCommand.ExecuteReader()
Do While objDR.Read
objCommand2.CommandText = "SELECT * FROM Sport WHERE PersonID = #PersonID "
objCommand2.Parameters.AddWithValue("#PersonID", objDR("ID"))
objDR2 = objCommand2.ExecuteReader
Loop
Catch ex As Exception
End Try
End Function
You can use multiple data readers if you use MARS - Multiple Active Result Sets - but I wouldn't advise that unless you really need it.
Instead, I'd suggest creating a new SqlConnection object each time you need it - use it for as short a period as you can, then dispose of it (use a Using statement to do this for you). The connection pool will take care of the efficiency in terms of reusing "physical" network connections where possible. That way you don't need to worry about whether the SqlConnection is already open etc - you just always follow the same "create, open, use, dispose" pattern every time.

vb error: Value of type 'String' cannot be converted to 'System.Data.SqlClient.SqlCommand'

I'm a novice VB programmer and I'm sure this solution is trivial, however, I am getting the above error when I try to display the results of one of my Stored Procs in SQL Server which doesn't need any parameters. How can I fix this?
My code excerpt:
Dim SQLCmd as SQLCommand = new SQLCommand()
SQLCmd.CommandText = "Exec AllTableCount"
SQLCmd.CommandType = CommandType.StoredProcedure
SQLCmd.Connection = GlobalFunctions.GlobalF.GetDevSQLServerStoredProcedure(SQLCmd.CommandType)
SQLCmd.ExecuteNonQuery()
MsgBox(SQLCmd.ExecuteNonQuery)
Where GetDevSQLServerStoredProcedure is defined in a different file as:
Public Shared Function GetDevSQLServerStoredProcedure(ByVal SQL As String)
Dim DBConn As SQLConnection
Dim DBCommand As SQLDataAdapter
Dim DSPageData As New System.Data.DataSet
DBConn = New SQLConnection(ConfigurationSettings.AppSettings("AMDMetricsDevConnectionString"))
DBCommand = New SQLDataAdapter(SQL) 'This is the line it errors on'
DBCommand.Fill(DSPageData, "Exceptions")
Return DSPageData
End Function
I can see this SP from VS 2008 in the Server Explorer. So the problem seems to be that I don't know how to connect a data adapter to an SP. Just a string query.
Command text should just be the name of the stored procedure as Tim mentioned.
It looks like the problem you are having now is that you are passinging the CommandType to your method GetDevSQLServerStoredProcedure instead of a string.