restore sql localdb with vb.net - vb.net

I am trying to retrieve a backup copy of the sql localdb through the environment of .net , but I get error .
the error : RESTORE cannot process database 'C:\Users\Emad-VB\Desktop\KizeN\KizeN\bin\Debug\Data\Data\DataStore.mdf' because it is in use by this session. It is recommended that the master database be used when performing this operation. RESTORE DATABASE is terminating abnormally.
the sql Query :
RESTORE DATABASE [C:\Users\Emad-VB\Desktop\KizeN\KizeN\bin\Debug\Data\Data\DataStore.mdf] FROM disk='C:\Users\Emad-VB\Desktop\bac\test.bac'
I tried again to use the database master to make restore but i get this error .
the error :
Incorrect syntax near 'Go'.
the sql Query :
use master
Go
RESTORE DATABASE [C:\Users\Emad-VB\Desktop\KizeN\KizeN\bin\Debug\Data\Data\DataStore.mdf] FROM disk='C:\Users\Emad-VB\Desktop\bac\test.bac'
This is the code that executes sql queries ....
Sub query(ByVal que As String)
'On Error Resume Next
Try
con = New SqlConnection(My.Settings.KConS)
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd = New SqlCommand
cmd.Connection = con
cmd.CommandType = CommandType.Text
Dim mm As String = " que"
cmd.CommandText = mm
cmd.ExecuteNonQuery()
If con.State = ConnectionState.Open Then
con.Close()
End If
Catch ex As Exception
End Try
End Sub
What is the solution to be able to retrieve the local database and Thanks

I see two problems:
"GO" is not a t-sql command. It is only meanigful to SQL utilities,
such as SQL Server Management Studio, so you shouldn't use it in
code that is being sent directly to the server.
I am not sure that you can change the databse within a connection by using "USE
MASTER". Instead you should create another connection string for
"master" and use it when you inititalize the connection that will perform the restore.

Related

Can't access Local SQL database manually by connection string in VB.NET using Visual Studio

I have a project set up with 3 separate tables. I used the built-in designer from Visual Studio.
The tables contain
Students
Courses
Tests in each course
All the tables share a studentnumber.
I have no problem getting and accessing the data true different tableadapters and corresponding bindingsources automatically generated by Visual Studio when I "drag and drop" them on the forms. I also am able to use the query builder to get the data I need from each table.
My problem occurs when I try to access the database manually via connection string.
I get this error:
Cannot attach file local path\HovedDatabase.mdf as database Outcomes because the file is already in use for database local path\HovedDatabase.mdf
This is the code I have:
Private Sub FormPrøver3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'StudentDataSet.StudentTabell' table. You can move, or remove it, as needed.
Me.StudentTabellTableAdapter.Fill(Me.StudentDataSet.StudentTabell)
Me.StudentTabellTableAdapter.Connection.Close()
Get_Data_Manualy_Fag()
End Sub
Private Sub Get_Data_Manualy_Fag()
Try
'Create variabals for inputcontainer
Dim Studnr As String = Me.StudentnrLabel1.Text
'Create a connection to the DataBase
Dim myConn As SqlConnection
myConn = New SqlConnection("Initial Catalog=OutComes;Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\HovedDatabase.mdf;Integrated Security=True")
'Create a Command object.
Dim myCmd As SqlCommand
myCmd = myConn.CreateCommand
myCmd.CommandText = "SELECT Fag FROM Fag3Tabell WHERE Fag = #Studnr"
myCmd.Parameters.AddWithValue("#Studnr", Studnr)
'Open the connection.
myConn.Open()
'Process the answer
Dim myreader As SqlDataReader
myreader = myCmd.ExecuteReader
'Traverse the DataSet and Display :
Dim i As Integer = 0
Do While myreader.Read()
Me.ComboBox1.Items.Add(myreader.GetString(i))
i = i + 1
Loop
'Close the connection
myConn.Close()
'Handle errors
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
I set up a similar project with a similar LocalSQL database. I have done nothing in Visual Studio other than creating the database with the same tables.
Here I have no problem connecting to the database via manual connection string.
My question is: why can't I access the local DB with a connection string in the first project?
You haven't posted your other connection string, but it looks like AttachDbFilename may be the problem. The DB will already be attached, this option is only meant to be used in single-user mode (one connection only).
Best bet is to permanently attach the DB to the LocalDB instance if that is what you are using the whole time.

havin issues inserting data into mysql using vb.net. it's keeps telling me connection already open [duplicate]

This error keeps popping up!!! An unhandled exception of type 'System.InvalidOperationException' occurred in MySql.Data.dll
Additional information: The connection is already open.
Dim cmd As MySqlCommand
con.Open()
Try
cmd = con.CreateCommand()
cmd.CommandText = "update animal_sale set #NOAB,#Amount,#Tax,#Total where Species=#Species"
cmd.Parameters.AddWithValue("#Species", TextBoxSpecies.Text)
cmd.Parameters.AddWithValue("#NOAB", TextBoxNo.Text)
cmd.Parameters.AddWithValue("#Amount", TextBoxAmount.Text)
cmd.Parameters.AddWithValue("#Tax", TextBoxTax.Text)
cmd.Parameters.AddWithValue("#Total", TextBoxTotal.Text)
cmd.ExecuteNonQuery()
load()
Catch ex As Exception
End Try
End Sub
It looks like you are not closing the connection after executing the query. You only have
con.Open()
and are not closing the connection after
cmd.ExecuteNonQuery()
Keep your database objects local to the method where they are used. Then you always know the state of a connection and can be sure they are closed and disposed. Using...End Using blocks do this for you even if there is an error. In this code both the connection and the command are covered by a single Using block. Note the comma at the end of the first Using line.
You can pass your connection string directly to the constructor of the connection.
You can pass your command text and the connection directly to the constructor of the command.
You Update sql command is not correct. You need to tell the server what fields to update. I had to guess at the names of the fields. Check you database for the correct names and adjust the code accordingly.
Please don't use .AddWithValue. See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
Here is another
https://andrevdm.blogspot.com/2010/12/parameterised-queriesdont-use.html
I had to guess at the datatypes and field size for the .Add method. Check you database for the correct values and adjust the code.
I converted the text box strings to the proper datatype here in the database code but normally these values would be parsed and converted before they reach this code.
Private Sub UpdateSale()
Using con As New MySqlConnection("Your connection string"),
cmd As New MySqlCommand("update animal_sale set nonab = #NOAB, amount = #Amount, tax = #Tax, total = #Total where species = #Species;", con)
cmd.Parameters.Add("#Species", MySqlDbType.VarChar, 100).Value = TextBoxSpecies.Text
cmd.Parameters.Add("#NOAB", MySqlDbType.Int32).Value = CInt(TextBoxNo.Text)
cmd.Parameters.Add("#Amount", MySqlDbType.Decimal).Value = CDec(TextBoxAmount.Text)
cmd.Parameters.Add("#Tax", MySqlDbType.Decimal).Value = CDec(TextBoxTax.Text)
cmd.Parameters.Add("#Total", MySqlDbType.Decimal).Value = CDec(TextBoxTotal.Text)
con.Open
cmd.ExecuteNonQuery()
End Using
End Sub

How can I allow multiple users to access/edit a microsoft access database?

Now I know right off the bat that Microsoft access isn't the ideal client for multiple users accessing it but it's the only one I've got right now. I have built a small program as a sort of inventory management system. There are currently three users that will be using it regularly and at the same time. One issue I am running into with this is that sometimes the database will not be accessible and will give an error stating that the file is already in use by "so and so" user. The other issue is that I'm getting a similar error every now and then where it states "The database has been placed in a state by user on machine that prevents it from being opened or locked". I am connecting to the database through an ACE OLEDB connection using the line below
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\Tool & Cutter Grinding\Tool Cutter Database.accdb;Persist Security Info = False"
I have also changed some of the settings in the actual access database such as:
Enable all macros
Add the folder the database is in to the trusted locations list
Confirm that the database is set to open in shared mode by default
I don't know if there is something small I've missed or a setting I need to change but as of yet, the problem is still persisting.
Below is an example of how I am using the database. I am using string based SQL commands but am not too familiar with DataSet/DataTable/etc. items, so I may be doing something incorrectly.
'close connection from any previous session
con.Close()
'clear dataset so as not to append data
ds.Clear()
'Select SQL query that selects ALL records from a table
Dim str As String = "SELECT * FROM " & "[" & table & "]" & ""
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\Tool & Cutter Grinding\Tool Cutter Database.accdb;Persist Security Info = False"
'use try catch statement to open the connection
Try
con.Open()
Catch ex As Exception
MsgBox(Convert.ToString(ex))
End Try
'use try catch statement to add a table (dt) to the dataset (ds) in order to store values
Try
ds.Tables.Add(dt)
Catch ex As Exception
End Try
'create new dataadapter object using the sql string from above and the connection created above
da = New OleDbDataAdapter(str, con)
'create new command builder in order to excecute the SELECT SQL statement using the dataadapter created (da)
'specify prefix and suffix for cb
Dim cb = New OleDbCommandBuilder(da) With {
.QuotePrefix = "[",
.QuoteSuffix = "]"
}
'use try catch statement to fill the datatable (dt) using the dataadapter (da)
Try
da.Fill(dt)
Catch ex As Exception
MsgBox(Convert.ToString(ex))
End Try
'set the datasource of the datagridview to the datatable
dgv.DataSource = dt.DefaultView
'close the connection to the database
con.Close()
Go to your Back-End Access DB file. File > Options > Client Settings. For your Use Case No Locks should be fine, but Edited record setting will work as well if you need it
but its [sic] the only one I've got right now
Actually, it's not.
Have a look at SQL Server Compact. It's free, it's small and it handles multiple users with aplomb.
You can add all the references you need using NuGet.

Restore database in SQL LocalDB using VB.NET

I have a project developed in VB.NET and SQL Server 2012 LocalDB (v11) and I am need backup/restore facility in my application. Backup part is complete but I am stuck at restore part. This is the query I want to be worked (and its working fine in SQL Editor)
ALTER DATABASE [<.MDF File Path>]
SET SINGLE_USER WITH ROLLBACK IMMEDIATE
RESTORE DATABASE [<.MDF File Path] FROM DISK='<.bak File Path'
and here is the code in VB.NET I am trying to execute
Sub Restorequery(ByVal que As String)
MainForm.Conn.Close()
con = New SqlConnection("Data Source=(LocalDB)\v11.0;Database=Master;integrated security=True;")
If Not con.State = ConnectionState.Open Then con.Open()
cmd = New SqlCommand(que, con)
cmd.ExecuteNonQuery()
End Sub
And here are the approaches I tried so far
Using the same query as above
Restorequery("ALTER DATABASE [<.MDF File Path>] SET SINGLE_USER WITH ROLLBACK IMMEDIATE")
Restorequery("restore database [<.MDF File Path>] from disk='<.bak File Path>'")
and this results in an error
Exclusive access could not be obtained because the database is in use. RESTORE DATABASE is terminating abnormally.
After finding reason for above issue (which is nonsense even after using master database while opening connection and closing all the previously opened connections using MainForm.Conn.Close() ), I tried second approach as per some links and references from Stackoverflow. And here are the queries I tried:
Restorequery("use [master] ")
Restorequery("alter database [<.MDF File Name>] set single_user with rollback immediate")
Restorequery("restore database[<.MDF File Name>] from disk='<.bak File Name>'")
Restorequery("alter database [<.MDF File Name>] set multi_user")
Restorequery("use [<.MDF File Name>]")
and here is the error I got while executing second query :
Additional information: User does not have permission to alter database <.MDF File Name with Path>, the database does not exist, or the database is not in a state that allows access checks. ALTER DATABASE statement failed.
Is there any other way to restore a SQL Server LocalDB using VB.NET ?
I have Used this code in one of my project.
Try
With OpenFileDialog1
.Filter = ("DB Backup File|*.bak;")
.FilterIndex = 4
End With
OpenFileDialog1.FileName = ""
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
Cursor = Cursors.WaitCursor
SqlConnection.ClearAllPools()
con = New SqlConnection(cs)
con.Open()
Dim cb As String = "USE Master ALTER DATABASE [" & System.Windows.Forms.Application.StartupPath & "\BRH.mdf] SET Single_User WITH Rollback Immediate Restore database [" & System.Windows.Forms.Application.StartupPath & "\BRH.mdf] FROM disk='" & OpenFileDialog1.FileName & "' WITH REPLACE ALTER DATABASE [" & System.Windows.Forms.Application.StartupPath & "\BRH.mdf] SET Multi_User "
cmd = New SqlCommand(cb)
cmd.Connection = con
cmd.ExecuteReader()
con.Close()
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

Restoring a backup using SQLCommand in VB.NET

I've got a VB.NET console application I'm creating that will make it easier for people to work with some test databases, and part of this is having a function that restores the database. I thought it was fairly straightforward, and here is the code I have so far:
Sub Restore()
con = New SqlConnection("Data Source=" & utilnamespace.sqlSvr & ";Database=Master;integrated security=SSPI;")
cmd = New SqlCommand("ALTER DATABASE [db] SET OFFLINE WITH ROLLBACK IMMEDIATE RESTORE DATABASE db FROM DISK = 'G:\db.bak' WITH REPLACE, STATS = 10", con)
cmd.Connection.Open()
cmd.ExecuteNonQuery()
Console.WriteLine(cmd.CommandText)
cmd.Connection.Close()
End Sub
The SQL works fine if I run it in SSMS, however it will time out if I try to run it from the app. The problem is that I've read over this and I'm still unsure of what to do.
Should I use BeginExecuteNonQuery and then have it listen for the statement complete message somehow?
Even if I believe that showing a waiting form and waiting for some kind of confirmation would be better for the end user... have you tried changing the timeout in the connection string to solve it in a quick way?
eg (seconds):
string connStr = "Data Source=(local);Initial Catalog=db;
Integrated Security=SSPI;Connection Timeout=30";
Also check these links:
SQL Server Management Objects (SMO)
SQL Server 2008 - Backup and Restore Databases using SMO
If the database is too big you can increase the timeout of the Command, not the connection string
cmd.Connection.Open()
cmd.CommandTimeout = 100
cmd.ExecuteNonQuery()
Console.WriteLine(cmd.CommandText)
cmd.Connection.Close()