Currently I used to back up my files in the way that, when user click on Backup the program will ask,
To Backup you must close your current session. This application will be closed now. Do you want to continue?
So the application will be closed and a new application will be launch in which if you click Backup it will copy the .mdf File and the .ldf File
|
But I have read in many pages that 'Copying the .mdf File and the .ldf File' is the unsafest way, so is there any other way to do Backup other than using SSMS because I want the user to be able to Backup within the Application.
|
Current code:
Sub Backup()
Dim con As New SqlClient.SqlConnection("data source=.\SQLEXPRESS;initial catalog=BQDB;Integrated Security=True")
Dim cmd As New SqlCommand()
Try
con.Open()
cmd.CommandType = CommandType.Text
cmd.CommandText = "Backup database BQDB To Disk='C:\Users\Zulfikar\BQBackup.BAK'"
cmd.Connection = con
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
|
Error Message Using Justin's Code
I tend to see a performance boost when using SqlCommands to backup databases.
Sub Backup()
Dim con As New SqlClient.SqlConnection("data source=DATASOURCE;initial catalog=NAME OF DATABASE;Integrated Security=True")
Dim cmd As New SqlCommand()
Try
con.Open()
cmd.CommandType = CommandType.Text
cmd.CommandText = "Backup database BQDB To Disk='C:\Users\Zulfikar\BQBackup.BAK'"
cmd.Connection = con
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Related
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.
Here is some VB.NET code for backing up our SQL Server 2014 database. When I run the code, the error message shown is "Incorrect syntax error".
Dim sqlcon As New SqlConnection With {.ConnectionString = "Server=USMAN; Database=test; Persist Security Info=True; User ID=sa; Password=123"}
Private Sub btnBackUp_Click(sender As Object, e As EventArgs) Handles btnBackUp.Click
SaveFileDialog1.FileName = DateAndTime.DateString + " - test"
SaveFileDialog1.Filter = "SQL Server database backup files|*.bak"
SaveFileDialog1.ShowDialog()
Dim cmdbak As New SqlCommand("backup database test to disk '" & SaveFileDialog1.FileName & "'", sqlcon)
sqlcon.Open()
cmdbak.ExecuteNonQuery()
MessageBox.Show("Backup has been successfully.")
sqlcon.Close()
End Sub
I am using this code to check my database for errors :
Dim cmd As New SqlCommand("DBCC CHECKDB (offpoDb) WITH TABLERESULTS", con)
cmd.ExecuteNonQuery()
But, u see, this command only generates SQL messages.
Is there any way to retrieve the messages in .net ?
Can i show the messages in a MessageBox ?
I've studied InfoMessage but i still fail to understand how to apply it/work with it.
Use a SqlDataReader instead of ExecuteNonQuery to get the recordset returned by TABLERESULTS:
Dim strBuilder As New System.Text.StringBuilder
Using cmd As New SqlClient.SqlCommand("DBCC CHECKDB (offpoDb) WITH TABLERESULTS", con)
Dim reader As SqlClient.SqlDataReader
reader = cmd.ExecuteReader
While reader.Read
strBuilder.AppendLine(CStr(reader("MessageText")))
End While
reader.Close()
End Using
MessageBox.Show(strBuilder.ToString)
To see all columns which are returned, execute the query in SQL Server Management Studio.
If you prefer to use the InfoMessage-event then add a handler and use it like following:
Sub MyMethod()
Using con As New SqlClient.SqlConnection("<yourConnectionString>")
con.Open()
AddHandler con.InfoMessage, AddressOf InfoMessage
Using cmd As New SqlClient.SqlCommand("DBCC CHECKDB (offpoDb)", con)
cmd.ExecuteNonQuery()
End Using
con.Close()
End Using
End Sub
Private Sub InfoMessage(sender As Object, e As SqlClient.SqlInfoMessageEventArgs)
MessageBox.Show(e.Message)
End Sub
I cannot insert records into a SQL Server CE database. I have read lots of articles but I still did not receive a proper answer for that.
This is my code. Database is located in the bin folder of the project.
Dim strConnection As String
strConnection = "Data Source=" + (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)) + "\\Barcode_UAT.sdf;Persist Security Info=False"
Dim cn As New SqlCeConnection(strConnection)
If cn.State = ConnectionState.Closed Then
cn.Open()
End If
Dim cmd As SqlCeCommand
Dim sql As String = "insert into [tbl_Barcodes] ([SerialNo],[ItemId],[Date]) values (#SerialNo,#ItemId,#Date)"
Try
cmd = New SqlCeCommand(sql, cn)
cmd.Parameters.AddWithValue("#SerialNo", "12121333")
cmd.Parameters.AddWithValue("#ItemId", "Item01010")
cmd.Parameters.AddWithValue("#Date", "2012-2-2")
cmd.ExecuteNonQuery()
cmd.Dispose()
Catch sqlexception As SqlCeException
MessageBox.Show(sqlexception.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
cn.Close()
End Try
It seems like you are missing the bin folder in your Data Source location path
I am trying to display query results from SQL server in VB. I wrote following code, but not getting how to "Just display the results";
Public Function ConnectToSQL() As String
Dim con As New SqlConnection
Try
con.ConnectionString = "Data Source=(local);Initial Catalog=TestDatabase;Persist Security Info=True;User ID=sa;Password=afm"
Dim cmd As New SqlCommand("SELECT username FROM users WHERE username='user'", con)
con.Open()
Console.WriteLine("Connection Opened")
' Execute Query
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
Console.WriteLine(String.Format("{0}, {1}", _
reader(0), reader(1)))
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection.
End Try
Return reader
End Function
Can any one guide? Thank you
I corrected a few things and now your function works fine for me:
Public Function ConnectToSQL() As String
Dim con As New SqlConnection
Dim reader As SqlDataReader
Try
con.ConnectionString = "Data Source=(local);Initial Catalog=TestDatabase;Persist Security Info=True;User ID=sa;Password=afm"
Dim cmd As New SqlCommand("SELECT username, WindowsLogin FROM users WHERE username='user'", con)
con.Open()
Console.WriteLine("Connection Opened")
' Execute Query '
reader = cmd.ExecuteReader()
While reader.Read()
Console.WriteLine(String.Format("{0}, {1}", _
reader(0), reader(1)))
'NOTE: (^^) You are trying to read 2 columns here, but you only '
' SELECT-ed one (username) originally... '
' , Also, you can call the columns by name(string), not just by number '
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection. '
End Try
'Return reader { note: reader is not valid after it is closed } '
Return "done"
End Function
Let me know if you have any questions.