Local SQL Server Backup Exception in vb.net - sql-server

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

Related

Backup Sql server Database with vb.net

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.

Getting Error when Restoring SQL Database using VB.net

Error Message: Exclusive access could not be obtained because the
database is in use. restore database is terminating abnormally.
My Backup code works but I don't know why this restore code doesn't work.
Try
Dim con2 As SqlConnection
Dim com2 As SqlCommand
Dim filename2 As String
Dim strquery2 As String
Dim database2 As String
Dim get_servername2 As String
'get the value selected in Database Name Dropdown Menu
database2 = Database_NameComboBox.Text
'get the value selected in Server Name Dropdown Menu
get_servername2 = Server_NameComboBox.Text.Trim
Dim opendlg As New OpenFileDialog
Dim constr2 As String
' set SQL connection data source using default Master Database
constr2 = "Data Source=" & get_servername2 & ";Initial Catalog=master;Integrated Security=SSPI"
' open SQL Database to restore
If opendlg.ShowDialog = Windows.Forms.DialogResult.OK Then
Me.Cursor = Cursors.WaitCursor
con2 = New SqlConnection(constr2)
con2.Open()
filename2 = opendlg.FileName
strquery2 = "Restore database " & database2 & " from disk='" & filename2 & "'"
' execute command
Try
com2 = New SqlCommand(strquery2, con2)
com2.ExecuteNonQuery()
MessageBox.Show("Database " & database2 & " has been Restored Successfully", "IBP Legal Aid Case Management System - Restore Database", MessageBoxButtons.OK, MessageBoxIcon.Information)
con2.Close()
Me.Server_NameComboBox.SelectedIndex = -1
Me.Database_NameComboBox.SelectedIndex = -1
Me.Database_NameComboBox.Enabled = False
Me.Cursor = Cursors.Default
Catch ex As Exception
Me.Cursor = Cursors.Default
MessageBox.Show(ex.Message)
End Try
End If
Catch ex As Exception
Me.Cursor = Cursors.Default
MessageBox.Show(ex.Message)
End Try
Prior to restore you should be sure there is no user connected to this database, otherwise you get the error you posted.
You can first set your db offline and then restore:
alter database MyDB set offline
with rollback immediate;
restore database ...

Managing Login Timeout Expired errors against SQL Server

I have the next VB.NET code being executed every hour. The code connects to that server and that database and execute some commands, not only on the database MyDatabase, but also on other databases in the same server.
As the user is a sysadmin, it has admin access to all databases without problem.
Dim ConnStr As String
Dim Conn As SqlConnection
Dim cM As SqlCommand
Try
ConnStr = "Server=MyServer;Database=MyDatabase;User Id=MyUsername;Password=MyPassword;Connect Timeout=300"
Dim Conn As New SqlConnection(ConnStr)
cM = New SqlCommand("", Conn) 'The SQL code comes from an script file (*.sql)
cM.CommandTimeout = 1800
cM.Connection = Conn
Conn.Open()
cM.ExecuteNonQuery()
Catch eX As Exception
Dim strError As String = ex.Message
If Not ex.InnerException Is Nothing Then strError &= " | " & ex.InnerException.Message
strError = "Connection Timeout: " & Conn.ConnectionTimeout.ToString & " | " & _
"Command Timeout: " & cM.CommandTimeout.ToString & " | " & _
strError
objLogging.LogErrorStep(JobID, JobName, CurrentStepName, strError)
Finally
If Conn.State = ConnectionState.Open Then Conn.Close()
Conn.Dispose()
End Try
The issue we are experimenting is that some of the runs of this job are failing because of Login Timeout Expired errors:
Connection Timeout: 300 | Command Timeout: 1800 | TCP Provider: Timeout error [258].
OLE DB provider "SQLNCLI10" for linked server "(null)" returned message "Login timeout expired".
OLE DB provider "SQLNCLI10" for linked server "(null)" returned message "Unable to complete login process due to delay in prelogin response".
As you can see in the code, I'm saving the errors in a Logging table, and also saving there the current Connection Timeout and the current Command Timeout.
My surprise is that when I'm checking the errors in my Logging table, I can see the elapsed time between the command started time and the command failed time, and the elapsed time has been only 15 seconds, when my Connection Timeout is set to 300. Look at the next image:
As you can see, the difference between the EventStart and the EventStop is about 15 seconds. If the process fails because of a Connection Timeout, and it is set to 300, the elapsed time should be 300, isn't it?
Thanks for your help and comments.
EDIT 2019-05-31
After wait for one more day having set the Connect Timeout = 300 property in the OPEDATASOURCE connectionString, I got a new Login Timeout Expired this afternoon, also just in 15 seconds (See the image)
The connect timeout and CommandTimeout settings apply to the connection from the client to "MyDatabase". Since your SQL Command connects to linked servers, those settings will not automatically be transferred and will have to be configured at the SQL Server level. Note that this change applies immediately and is server wide (T-SQL):
EXEC sp_configure 'remote login timeout', 300;
GO
RECONFIGURE ;
GO
EXEC sp_configure 'remote query timeout', 1800;
GO
RECONFIGURE ;
GO
See these two related MSDN links:
Remote Login Timeout
Remote Query Timeout

Excel VBA: ODBC SQL server driver query timeout expired

I have the below VBA query used in Excel 2016 that exacutes a MS Sql stored procedure, sometimes it executes smoothly and returns the recordset, but more often I get an error [Microsoft][ODBC SQL Server Driver] query timeout expired.
At the same time when we go to SSMS and execute the query it runs without issues.
This assumes the issue is rather caused by Excel/VB than by SQL or the query itself.
Searching for this error results in checking network firewalls, but we tried on other machines without firewalls, problems persists.
Here is the VB code:
Public Sub GetDataset2()
Dim cn As ADODB.Connection
Dim cm As Object
Dim rs As ADODB.Recordset
Dim UID, PWD, DB As String
UID = "userId"
PWD = "passworD"
DB = "192.168.1.1"
Set cn = New ADODB.Connection
Set cm = CreateObject("ADODB.Command")
cm.CommandTimeout = 0
cn.Open ("Driver={SQL Server};Server=" & DB & ";Database=myDatabaseName;Trusted_Connection=no;Timeout=900;Uid=" & UID & ";Pwd=" & PWD)
Set rs = cn.Execute("Get_dataset2 '" & Format(Range("dateFrom"), "yyyy-mm-dd") & "' ,'" & Format(Range("dateTo"), "yyyy-mm-dd") & "' ")
Dim lRow As Long
'Find the last non-blank cell in column A(1)
lRow = Sheets("data").Cells(Rows.Count, 1).End(xlUp).Row
lr = "A" & lRow + 1
Sheets("data").Range(lr).CopyFromRecordset rs 'insert data
cn.Close
End Sub
Any suggestion is appreciated.
Joel
After some more thought about the question and the comments on my prior answer, here are some additional points. To BitAccesser, cn.CommandTimeout is the same as Connection.CommandTimeout since the originally submitted code had already dimensioned and set the cn object as an ADODB.Connection. Also worth noting is the difference between ConnectionTimeout and CommandTimeout. The connection timeout is network level, while the command timeout is SQL Server level. In this case, even though a ADODB.Command object is instantiated, it isn't used. Another point relates to the connection string. The connection timeout could be referenced in the connection string, but often, is not used. The connection will be defaulted to 15 seconds. So, its worth resetting those attributes explicitly.
Cn.CommandTimeout = 50
Cn.ConnectionTimeout = 50
One possible solution is to lengthen the connection command timeout value. Your current script has the value set to 0. This could be increased. Running the query in SSMS should give you a rough idea of the time needed to complete the query. Then, adjust the value accordingly.
cm.CommandTimeout = 100
After weeks of testing various code changes, we found that when changing the SQL call to QueryTable method instead of CopyFromRecordset method, it is working fine.
So I am pasting the code if anyone needs it in future.
Sub GetDataset3()
Dim cn As ADODB.Connection
Dim Rs As ADODB.Recordset
Dim UID, PWD, SRV As String
UID = "userId"
PWD = "passworD"
SRV = "192.168.1.1"
If Sheets("data").QueryTables.Count = 0 Then
Sheets("data").Cells.Select
Selection.ClearContents
Dim Str As String 'adds backround query
Str = ""
For Each cell In Range("A1:A10").Cells
Str = Str & Chr(10) & cell
Next
With Sheets("data").QueryTables.Add(Connection:="ODBC;UID=;PWD=;DRIVER=SQL
Server;SERVER=SRV", Destination:=Range("a2"))
.CommandText = "select 1"
'BackgroundQuery = True
'.Refresh BackgroundQuery = True
.FieldNames = False
.AdjustColumnWidth = False
End With
End If
With Sheets("data").QueryTables(1)
.Connection = "ODBC;DRIVER=SQL Server;SERVER=" & SRV &
";database=myDatabaseName;UID=" & UID & ";Pwd=" & PWD &
";Trusted_Connection=no;APP=Microsoft Office"
.CommandText = ("Get_dataset2 '" & Range("dateFrom") & "' ,'" &
Range("dateTo") & "' ")
BackgroundQuery = True
.Refresh BackgroundQuery:=False
End With
End Sub

Requested operation requires an OLE DB Session object -- VB6 to SQL Server 2000

I'm attempting to get into a VB6 application that was written for a client about a decade back, but intermittently I keep getting this error. The application has a login required upon launch, and upon entering the login provided for me (I am 100% certain it is correct), the following error is given:
Run-time error '3709'
Requested operation requires an OLE DB Session
object, which is not supported by the current provider.
What's truly bizarre is that last night I was able to log in with absolutely no problems. However, I had this problem before about a week back, but I was out of town for several days and when I cam back I could log in again. Before that initial instance, I was able to log in fine. I noticed a similar question already posted, but the solution that was given did not work for me. Here's the code pertaining to establishing the database connection. Note, the Serv1, Use1, PW1 etc are just fillers for server names/usernames/passwords.
Public Function GetConnected()
' This function decides which server to connect and makes the connection
'Determines which connection string to use
If frmSplash.Text1 = "1" Or frmSplash.Text1 = "apc" Then 'server location
'determines if the logon contains '1' or 'apc'
'APC connection code
strSQLServerName = "(Serv1)"
strSQLDBUserName = "Use1"
strSQLDBPassword = "PW1"
strSQLPort = ""
ElseIf frmSplash.Text1 = "2" Then
'Laptop connection string
strSQLServerName = "(Serv1)"
strSQLDBUserName = "Use2"
strSQLDBPassword = "PW2"
strSQLPort = ""
Else
'Client connection code
strSQLServerName = "Serv2
strSQLDBUserName = "Use3"
strSQLDBPassword = "PW3"
strSQLPort = ""
End If 'server location
'If (m_DBConnection Is Nothing) Then
Set m_DBConnection = New ADODB.Connection
'End If
SessionLocation = frmSplash.LocationCombo.Text
'***************************************
'Connecs to database based on location
If frmSplash.LocationCombo.Text = "Loc1" Then
strSQLDBName = "ServLoc1"
ElseIf frmSplash.LocationCombo.Text = "Loc2" Then
strSQLDBName = "ServLoc2"
Else
strSQLDBName = "ServLoc3"
End If
'**************************
'Builds connection string
m_DBConnection.ConnectionString = "Provider=SQLOLEDB;" & _
"Data Source = '" & strSQLServerName & strSQLPort & "';" & _
"uid=" & strSQLDBUserName & ";" & _
"pwd=" & strSQLDBPassword & ";" & _
"Database=" & strSQLDBName & ";"
On Error GoTo errorhandler
m_DBConnection.Open
If (m_DBConnection Is Nothing) Then
MsgBox "Connection Failed"
End If
Exit Function
errorhandler:
MsgBox ("Problem with the Server")
'MsgBox "Connection State " & GetState(m_DBConnection.State)
End Function
Public Function ExecuteSQL(strSQL As String) As ADODB.Recordset
'Dim cmd As ADODB.Command
Set cmd = New ADODB.Command
**cmd.ActiveConnection = m_DBConnection** <-----(Error occurs here)
cmd.CommandType = adCmdText
cmd.CommandText = strSQL
Set ExecuteSQL = cmd.Execute
Exit Function
Variable definitions:
Public strSQLServerName 'Holds the name of the SQL Server
Public strSQLDBUserName 'Holds the user name (for SQL Server Authentication)
Public strSQLDBPassword 'Holds the password (for SQL Server Authentication)
Public strSQLDBName 'Holds name of a database on the server
Public strSQLPort 'Holds the Port Number
Public SessionUser As Integer ' To Track the type of User (3 Levels)
Public SessionLocation As String ' To Track the DB throughout the Session
Public m_DBConnection As ADODB.Connection
Public cmd As ADODB.Command
This is my first time working in VB6 and I'm a bit at a loss. I can't figure out why it works sometimes and not others. If anyone has any insights, they'd be very much appreciated.
Change your error handling to get a better idea of what is going on. Since you are setting your conncection (Set m_DBConnection = New ADODB.Connection) to a new object, your check (m_DBConnection Is Nothing) doesn't do much since the ojbect is certain to already exist.

Resources