I have written some codes in vb.net to backup a database in local computer. In many computers it work without problem. but in a specific computer I encounter with this error :*"Timeout expired. The timeout elapsed prior to completion of the operation or the server is not responding The backup or restore was aborted."
With SQL server Management I can backup without problem but with my codes I have problem.
Private Sub BackupDataBase()
Dim cnn_str As String = "Data Source=mycomputer\rb;Database=Master;integrated security=SSPI;"
Dim _backupFileName As String = "d:\backup.bak"
Dim query As String = "BACKUP DATABASE rb_db TO DISK='" & _backupFileName & "' WITH INIT"
Dim cnn As New SqlConnection(cnn_str)
Dim cmd As New SqlCommand(query, cnn)
Try
If cnn.State = ConnectionState.Closed Then cnn.Open()
cmd.ExecuteNonQuery()
MsgBox("Backup successful!")
Catch ex As Exception
MessageBox.Show("Backup failed!" & vbNewLine & Err.Description, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
A SqlCommand has a CommandTimeout value of 30 seconds by default. If the operation specified does not complete in that time period, an exception is thrown.
If your operation requires more than 30 seconds to complete, set the CommandTimeout to a greater value. The time to execute will depend on the system hardware and current load.
I don't know for sure but I suspect that the backup will still be performed, even if that exception is thrown by your application.
Related
I have a SQL StoredProcedure that performs two INSERT INTO operations in SSMS as expected.
When executing this SP in my VB.NET application, it is executing (no SqlException thrown in Try block) but not executing the INSERT INTO commands.
This application uses numerous SP's that all work without problems.
Code is as follows:
Using (ParentMDI.dbCon)
Dim sqlcmd As New SqlCommand("hyd_top_level_isr")
With sqlcmd
.CommandType = CommandType.StoredProcedure
.Parameters.AddWithValue("#part_num", part_num)
.Parameters.AddWithValue("#issue", issue)
End With
Try
sql.ExecuteNonQuery()
Catch ex As SqlException
If DialogResult.Yes = MessageBox.Show("Error inserting top-level ISR." & vbCrLf & vbCrLf & "Send Error Report?", "Workflow Error", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) Then
ParentMDI.emailerrorstring = "Stored Procedure: hyd_top_level_isr"
ParentMDI.emailerrormessage = ex.Message
ParentMDI.ErrorEmail()
End If
End Try
End Using
For clarification;
I have inserted breakpoints before ExecuteNonQuery(). The sub does execute the ExecuteNonQuery() and the parameters being passed are populated with the correct values.
I have also inserted a RETURN in the SP to return the SCOPE_IDENTITY(). This returns an empty string (not NULL, as I was expecting).
If any of you need more information, please let me know.
I will be massively appreciative of anyone who can educate me on where I'm going wrong!
(This is my first time ever asking for help, please be kind!) :)
EDIT:
Sorry guys. I seem to have lead you on incorrectly. The code pasted above is me trying all sorts of different attempts at trying to solve this. What I'll post now is what I should have posted in the first place. With the same outcome. Sorry for the confusion, and thanks for your attempts so far...
Dim sqlcmd As New SqlCommand("hyd_top_level_isr", ParentMDI.dbCon)
With sqlcmd
.CommandType = CommandType.StoredProcedure
.Parameters.AddWithValue("#part_num", part_num)
.Parameters.AddWithValue("#issue", issue)
End With
Try
sqlcmd.ExecuteNonQuery()
Catch ex As SqlException
If DialogResult.Yes = MessageBox.Show("Error inserting top-level ISR." & vbCrLf & vbCrLf & "Send Error Report?", "Workflow Error", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) Then
ParentMDI.emailerrorstring = "Stored Procedure: hyd_top_level_isr"
ParentMDI.emailerrormessage = ex.Message
ParentMDI.ErrorEmail()
End If
End Try
In addition to #Zohar Peled's comment I think you should set sqlCmd's connection and use sqlCmd.ExecuteNonQuery. Below you should also use local sqlConnection.
Using sqlcmd As New SqlCommand("hyd_top_level_isr", ParentMDI.dbCon)
With sqlcmd
.CommandType = CommandType.StoredProcedure
.Parameters.AddWithValue("#part_num", part_num)
.Parameters.AddWithValue("#issue", issue)
End With
Try
sqlCmd.ExecuteNonQuery()
Catch ex As SqlException
'' Handle exception here
End Try
End Using
Firstly I think that in SQLCommand you should pass the SQL connection like:
Dim sqlcmd As New SqlCommand("hyd_top_level_isr", ParentMDI.dbCon)
Secondly, you are not run sqlcmd but sql.executenonquery.
Third, executenonquery is an integer. If you dim a variable:
Dim result = sqlcmd.ExecuteNonQuery()
What do you get?
I have a local SQL Server database. Every time I want to take a backup, an exception occurs, I don't know how to handle it - please help me!
Here is my Code :
Public Function DBBackUp(DB_Address As String, Bckup_Address As String) As Boolean
Try
Dim ComStr As String = "BACKUP DATABASE [" & DB_Address & "] TO DISK = N'" & Bckup_Address & _
"' WITH NOFORMAT, INIT, NAME = N'MData" & _
"-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10 "
MyConnection = New SqlConnection(strConnection)
MyCommand = New SqlCommand(ComStr, MyConnection)
If MyConnection.State = ConnectionState.Closed Then MyConnection.Open()
MyConnection.ChangeDatabase("Master")
SqlConnection.ClearAllPools()
MyCommand.ExecuteNonQuery()
Return True
Catch ex As Exception
MsgBox("An Error Occurred." & vbCrLf & ex.Message)
Return False
Finally
MyCommand.Dispose()
If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
End Try
End Function
Exception message is :
Timeout expired. The timeout period elapsed prior to completion of
the operation or the server is not responding. The backup or restore
was aborted. 10 percent processed. 20 percent processed. 30 percent
processed. 40 percent processed. 50 percent processed. 60 percent
processed.
Try to Set the connection timeout in your connection. This timeout is exceeded due to a command which needs more time to process. Please tell me if it works
I am doing an excel macro in order to automate some query what eventually I run in SQL Server. My problem is that I don't know how the server could alert excel if a query did not succeed.
For example, I am importing a file, and there is no syntax error, but it might result in error if bulk insert statement is not set properly. For the SQL connection I use the following:
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
' Create the connection string.
sConnString = "Provider=SQLOLEDB;Data Source=localhost;" & _
"Initial Catalog=" & MyDatabase & ";" & _
"Integrated Security=SSPI;"
' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.Open sConnString
Set rs = conn.Execute(Myquery)
If I have a syntax error while compiling the code it stops which is good. But if I have another problem, e. g. the database name is not good, the table already exists, then the program runs with no error, I only can detect when I check it in SQL Server. I really want to know somehow whether the query run has resulted in error and then code some alerting message then into my macro. How can I do that?
Every help is much appreciated!
The ADO connection object has an Errors collection, which you can check after running your SQL:
conn.Errors.Clear
Set rs = conn.Execute(Myquery)
If conn.Errors.Count > 0 Then
For i = 0 To conn.Errors.Count
Debug.Print conn.Error(i).Number
Debug.Print conn.Error(i).Source
Debug.Print conn.Error(i).Description
next i
End If
That should get you started. You may find that you're seeing an 'error zero' that's actually a status message; if so, you'll have some additional coding to to do.
I found this helpful but needed to use:
Debug.Print conn.Errors.Item(i).Description
Debug.Print conn.Errors.Item(i).Source
Debug.Print conn.Errors.Item(i).NativeError
I might be using a different connection type
i need to call a function that do some query while another connection is opened and its doing a transaction.
Ok i get this is weird, here some code:
Main part:
Using connection As New SqlConnection(connectionString)
connection.Open()
Dim command As SqlCommand = connection.CreateCommand()
Dim transaction As SqlTransaction
transaction = connection.BeginTransaction("myTransaction")
command.Connection = connection
command.Transaction = transaction
command.CommandText = sSQL
Try
command.ExecuteNonQuery()
Dim functionResult As String = myFunction(param1, param2)
If functionResult <> "" Then
'error! i need to rollback the first query done here!
transaction.Rollback()
else
transaction.Commit()
End If
Catch ex As Exception
transaction.Rollback()
End Try
End If
End Using
myFunction do lot of stuff, and a lot of querys. Every query needs to reopen connection (without transaction this time) but everytime i try to execute the first query inside my function i got timeout error from database (after 30 seconds).
I know i can do this work "copy-pasting" all the myFunction code inside that already opened connection and using the already opened connection, but i use that function more than once and i don't want to mess up my code.
How can i solve this?
edit for more information:
that was an already reduced version of the code i'm using, but here a reduced version on what "myFunction" do:
Dim connectionString As String = "my connection string"
Dim queryString As String = "SELECT id FROM foo WHERE param1 = #myValue"
Dim ds As DataSet = New DataSet()
Try
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(queryString, connection)
connection.Open()
command.CommandText = queryString
command.Parameters.Add("#myValue", SqlDbType.Int).Value = 10
Dim adapter As New SqlDataAdapter()
adapter.SelectCommand = command
adapter.Fill(ds, "randomName")
If ds.Tables("randomName").Rows.Count < 0 Then
'error!
connection.Close()
Return "error"
End If
End Using
Catch ex As Exception
Return "Database error - " & ex.Message
End Try
The code execution (even in debug) freeze on the adapter.Fill(ds, "randomName") command for 30 seconds, after that i get a timout error
You can use as many connections as you want, just make sure they don't interfere with each other. SQL server is very diligent about preserving data integrity, so if one uncommitted transaction conflicts with another uncommitted transaction, you get a deadlock.
You may want to play with transaction isolation level, default is READ COMMITTED for SQL server, try to set it to READ UNCOMMITTED. Please read the docs to be aware of the consequences.
From the above link:
In SQL Server, you can also minimize locking contention while protecting transactions from dirty reads of uncommitted data modifications using either:
The READ COMMITTED isolation level with the READ_COMMITTED_SNAPSHOT database option set to ON.
The SNAPSHOT isolation level.
I have an old visual basic 6 application when some users reported me errors when the computer going back from sleep. This problem did not occurs on every client computer, (I would say some Windows 7). If the vb6 application was still open then if they try to use this application it crashes with the following error message.
I debugged and I found the problem: I have a global variable that keep the connection to the database. This variable is initialized only once in the beginning of the application. When the computer going to sleep and go back some times later, the status of this variable is still "OPEN" but in fact the connection is lost! If I "CLOSE" and then "OPEN" this variable connection I am able to query the database.
I wonder if this is normal that I lost my database connection?!
Here is some code:
' This is my global variable
Global cn As New ADODB.Connection
' Set connection properties for sql server.
cn.ConnectionTimeout = 25
cn.Provider = "sqloledb"
cn.Properties("Data Source").Value = ".\SQL2008"
cn.Properties("Initial Catalog").Value = DB_INITIAL_CATALOG
cn.Properties("User ID").Value = DB_USERNAME
cn.Properties("Password").Value = DB_PASSWORD
cn.Open
' This is a typical query on my database
Set rs = New ADODB.Recordset
strSql = "SELECT * FROM tblUsers"
rs.Open strSql, cn, adOpenKeyset
Any idea?
Thanks.
Yes, I've seen this kind of thing before. There may be settings on the connect string that can help reduce it, but time outs and/or network drops can break the underlying (often TCP) connection to the DB server. You then see the error manifest itself in the next I/O to the database.
I recommend wrapping access to the shared connection so you can transparently catch that specific error and retry. Keep the connection private in a class or module and have methods such as:
'Open is called to set the args to connect, these should be saved for reconnect
Public Sub Open(connect params here)
'save arsg to prive members to reconnect
'connect to db
End Sub
Public Function OpenKeyset(sql) As RecordSet
Set rs = New ADODB.Recordset
On Error Resume Next
rs.Open strSql, privateConn, adOpenKeyset
'if the error is the disconnect
If Error.Number = xxx Then 'or inspect the error message or error collection
'turn of error trap
Err.Clear
On Error Goto 0
'reopen db conn
'then retry
rs.Open strSql, privateConn, adOpenKeyset
End If
OpenKeyset = rs
End Function
You could even periodically perform a no-op db operation like quering the catalog or whatever to keep the connection live and proactivle reconnect. You couild also watch for large jumps in time that happen if a computer hibernates.
You should trap the sleep and wake events in your vb6 code, any long running queries should be closed at sleep, so that the dB connection can be closed. At wake, you do the opposite. You need to listen to
WM_POWERBROADCAST message.https://msdn.microsoft.com/en-us/library/windows/desktop/aa373247(v=vs.85).aspx
Good luck
Jeppe