Restore a SQL .bak file using a VB script? - sql

I am exploring methods to enable users to restore a database from within the project.
I have a project which I want to publish together with the database, so that users with no experience can use the program I have developed.
The code is written in VB script and I am able to publish the VB code, but am finding it difficult to include the database in the ClickOnce method.
I have been thinking that I could possibly copy the .bak file to the client's PC and then run a VB script that restores the database to the SQLserver that is installed in the ClickOnce install.
Has anyone ever done this?
I did find on the web something that looked promising, but it has been written for .NET framework 2.0 or 3.0 and I found that when I added System.Data.SqlClient 4.8.0 I got the following error:
Severity Code Description Project File Line Suppression State
Error Could not install package 'System.Data.SqlClient 4.8.0'. You are trying to install this package into a project that targets '.NETFramework,Version=v2.0', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.
The website where I got the code: http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=1433&lngWId=10
Please can anyone help?

VBScript, which would get run via wscript.exe is decades old technology
VB.NET, which would get compiled into a custom .exe or .dll, is 2005+ (not included in this is .net core which is the past few years but I've not touched it)
dim connectionString as string = "Provider=MSOLEDBSQL;Server=localhost;Database=myDataBase;Trusted_Connection=yes;"
dim connection as New OleDbConnection(connectionString)
Dim cmd As New OleDbCommand
Dim query As String = "RESTORE DATABASE AdventureWorks2012 FROM AdventureWorksBackups;"
Try
cmd.CommandText = query
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("something bad happened")
End Try
Reference bits
ExecuteNonQuery https://learn.microsoft.com/en-us/dotnet/api/system.data.oledb.oledbcommand.executenonquery?view=netframework-4.8
Restore database https://learn.microsoft.com/en-us/sql/t-sql/statements/restore-statements-transact-sql?view=sql-server-ver15
and if you're not using OLEDB, or need a different provider, then futz with connection string as needed but that's the general approach

Related

VB.NET to connec to MDB file using windows default ODBC JET driver

I am building a Windows Winforms Desktop Application using VB.NET 6.0.5, Visual Basic, and Visual Studio Community 2022.
I used to connect to ACCDB File using Microsoft Access Database Engine.
It's working well in the development machine, but when I try to deploy to a fresh installation of a Windows 10 x64 machine; I have to let the setup download and install the ACE engine.
I want to reduce the prerequisites as much as possible, as the end-users already have to download and install the .NET 6 Runtime.
I found out that all versions of Windows come by default with Microsoft Access Driver (*.mdb) and I want to use that.
The driver location is: C:\Windows\SysWOW64\odbcad32.exe
I think if someone installed Office it might update the driver to a different Jet.OLEDB version.
So my question is:
How to check the current Jet.OLEDB driver's version and what would be the connection string?
My current connection string is:
Dim cStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Database.mdb;User ID=Admin;Password=123;"
But still, it's giving that Microsoft.Jet.OLEDB.4.0 Provider is not registered.
I know that ACE Engine and ACCDB work better but it's enough for me to use JET and MDB.
Please help!
Thank you
Update: 20/5/2022
Things that I tried but with no success:
I compiled the application to target x86 as it's said in many references that Jet.OLEDB doesn't support x64.
I tried Provider=Microsoft.Jet.OLEDB.10.0.
Well, if you wondering what the connection string should be?
Let VS build it for you.
(you don't want to hand code, or type in connection strings anyway - and you don't have to).
So, in setting for your VS project, then here:
So, let click on that [...] and build the connection using JET (as opposed to ACE).
However, your issue/problem is that NOW vs2022 is x64 bits (first version to be that way).
I'm running 2019, so it will STILL test and VERIFY a x32 bit connection. I suspect that vs2022 WILL NOT pass the "test" button, but you STILL can use it to build the conneciton.
So, in above, we start the connection wizard, - hit change for the defaulted sql server, and we now have this choice:
Ok, we selected Access, but what about JET vs ACE.
Well, click on advanced - this:
And now we can (get to) choose the provider.
this:
So, you can choose jet or ACE.
choosing jet, then we now back to here:
Now BECAUSE I am running vs2019, then my test connection WILL work!!! - for you, it probably will not. So, the test connection button for you - you can try it, but EVEN if it gives a fail message, your connection is still ok.
This:
Ok, at this point, we are done.
We now in code can use the above connection in our code. Say like this:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Using conn As New OleDbConnection(My.Settings.TestJET)
Using cmdSQL As New OleDbCommand("SELECT * FROM tblHotels", conn)
conn.Open()
Dim rstData As New DataTable
rstData.Load(cmdSQL.ExecuteReader)
Dim strMSG As String =
"There are " & rstData.Rows.Count & " Hotels in the database " & vbCrLf &
"The first Hotel is " & rstData.Rows(0).Item("HotelName")
MsgBox(strMSG, MsgBoxStyle.Information, "Table info")
End Using
End Using
End Sub
And we get this:
Now, I suppose I could look at the connection string - but I never really do that - I always let the system build that for me.
I get this:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\test\Rides_be.mdb
As you noted, MAKE sure your project is set to x32. However, since you running vs2022, then the connection builder should work, but you HAVE to run your project to test that connection, I don't think in vs2022, you can use "test" connection.
On the other hand, since most of office (and even Access ACE is x64 bits?). Then if you build a connection using x64 bit ACE, then your test connection button should work.

Windows 10 Universal App, Reference Local SQLite DB file

I'm getting closer to having a functional SQLite Database in my Universal App.
I keep getting the error 'Cannot Open' and I feel it might be a path problem as SQL Toolbox for Visual Studio picks up the .db file fine.
How to I reference the .db should i put it in a new folder? I need to perform operations to this database but information on this in VB.NET is extremely limited!
Here is what I have so far:
Dim platform As New SQLite.Net.Platform.WinRT.SQLitePlatformWinRT
Dim lc As New SQLite.Net.SQLiteConnection(platform, "/myDB.db")
lc.Execute("INSERT INTO lcCust (CName) VALUES ('Hello')")
I have now successfully created a db using a GUI program. This one specify is SQLiteStudio. I created the DB and connected to it using the SQLite-PCL package along with the Visual Studio addon

Visual Studio 2013 SQL Query and View Designer not appearing

Not sure why the Query and View Designer is not appearing as per
http://msdn.microsoft.com/en-us/library/vstudio/ms172013.aspx
It's an ASP.net project with database in the AppData folder, and a connection using SQL 2008 Express.
If it helps the connection string is:
Data Source=.\SQLEXPRESS;AttachDbFilename="C:\folders...\App_Data\database.mdf";Integrated Security=True;Connect Timeout=30;User Instance=True
If I open the project in VS2012 (where I've worked on this project for some time), find a table, right click, new query, I get the nice interactive visual design tool.
If I open the project in VS2013 (just installed) and do the same, blank page named SQLQuery1.sql and a basic connection to SQL Express (ie. master, model, etc.)
MS page tells me Tools / Options / Visual Database tools - but this doesn't exist on my installation!
Am I missing something?
Also tried with blank project, added App_Data and a new database (so using LocalDB), added a table, right click, new query - exactly the same blank file.
I have been having the same problem and think I have found the solution.
When you are adding the connection to the Database, in the Add Connection Dialog.
Click 'Change...' next to the Data source
Dialog opens showing 'Change Data Source'
You probable have selected 'Microsoft SQL Server' and then below that there is a drop down where you can select:
.NET Framework Data Provider for OLE DB
.NET Framework Data Provider for SQL Server (This is probably selected by default)
try changing to the OLE DB connection.
Click OK, and then complete the rest of the connection on the 'Add Connection' dialog.
I have then found that using the database works as it did in VS2012 and as you are describing above.
Was searching for a solution to a similar issue. Unable to use Query Designer for a local mdf file database. This is what I found...hope it helps someone.
Reading the comments here (http://social.msdn.microsoft.com/Forums/sqlserver/en-US/ed4675d3-aa84-47db-bdf5-f852355409e6/query-designer-not-displaying-in-visual-studio-2013?forum=ssdt).
According to the moderator of that forum question (Kevin Cunnane of Microsoft), "in Visual Studio 2013 the query designer and database diagram features are no longer available from the Server Explorer. If you wish to keep using the query designer, the only other workaround for now is to access it from SSMS. "
My current workaround is to use Visual Studio 2012 Server Explorer to view data and write queries for a local MDF file. And to use Visual Studio 2013 for everything else.
I have researched about 5 minutes how to run a query in Visual Studio. At the end I found this:
Even though i followed same steps , It did not work at once it gave some error and Studio closed. It was problem at my end and unknowingly it got sorted out on its own.
This component is called "SQL Server Data Tools". You can download it from MSDN. I found this page simply by googling "vs2013 ssdt". It seems that what TsugaSoft posted is true, however you still can install this component separetely... And it also works for Visual Studio 2012.

How to start creating and using databases?

I need a database for a web project (and for off-line projects as well). The problem is I don't know where to start and googling returns more advanced stuff. Where do I start?
I already have Visual Studio 2010 and Visual Web Developer 2010 installed (both – the express version). I'm not sure I have what is needed for SQL (which, correct me if I'm wrong, is what I need for databases). In my start button I have two folders named "Microsoft SQL Server 2008" (one of them with an "R2" at the end). But my computer isn't a server, just a PC. Am I supposed to install something on my PC? If so – which of the two? (The one with the "R2" or the one without it)
All I need is to create a simple database so I can store and retrieve information easily instead of reading a text file....
well, you need SQL Server installed. Try searching your computer for it, you may have it installed. The easiest way is to run services.msc and look for SQL Server.
See here, I have 3 instances installed but just one running (INSTANCE2008 is the name I gave to it, you will probably have SQLEXPRESS or MSSQLSERVER):
If it is installed you will need SQL Server Management Studio to create your database. You will probably have it under:
once you access it, just connect to your server (usually called localhost), right click on the database folders and select "new database"
from that, it is really easy to create your DB, just follow the steps
Sounds like you have all the tools you need to get started, however you might also need SQL Management Studio as well.
But "How to start creating and using databases?" is sort of a broad question. If your question is really about application design, then you would start 'creating databases' when you've defined your model. Once your model is defined, then you can start creating the database.
If your question really is about creating and using databases, SQL Management Studio should get you on the right track. It's a point n' click way to creating databases, tables, stored procs, etc.
Using the database... hmmm. The easiest way is to integrate Microsoft's Enterprise Library 5. Again, point n' click interface to setting up the connection in your web.config (or app.config) and plenty of examples.
You can import the System.Data and System.Data.SqlClient library in your application, like
using System.Data;
using System.Data.SqlClient;
and research about the SqlConnection class.
about SQL Statements, the W3Schools has a good reference.
A simple method sample that has a connection
protected void connection()
{
using(SqlConnection conex = new SqlConnection("your_connection_string"))
{
SqlCommand comand = new SqlCommand();
comand.CommandText = "SELECT * FROM Table";
comand.CommandType = CommandType.Text;
comand.Connection = conex;
conex.Open();
comand.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(comand);
DataTable dt = new DataTable();
da.fill(dt);
}
}
You will be having your database on your server. You can directly connect to that database with just a slight configuration in web.config.
OR
If you found "SQL Server Management Studio" in your Microsoft SQL Server 2008 R2 click on it and login to the sql server / express instance of the sql server.
Create the database there.

how to create a setup in vb.net ? ? with example

cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=C:\solutionvs10\test\test\bin\Debug\db2.mdb;**Jet OLEDB:Database Password=secret**")
cn.Open()
''# codes
cn.Close()
I used V S 2010
The above is my code......u can see that it is Ms Access DataBase....(password protection)
How i can create a setup .....that can be easy to install other computer.........
Can i Create such a setup ???
First of all, this code you posted is wrong:
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=C:\solutionvs10\test\test\bin\Debug\db2.mdb;**Jet OLEDB:Database Password=secret**")
cn.Open()
''# codes
cn.Close()
The reason it's wrong is because you're not guaranteed to close your database connections, eventually leading to a state where your database is not accessible to your application. This won't happen in your development testing, because such tests tend to be short-lived, but it will happen to your users, who tend the keep applications running over longer periods of time.
Now, I know you're thinking, "Yes, I am closing my connections. Don't you see the cn.Close()?" Yes, I see it. But that's not good enough. There are a few cases (exceptions are the big one) that can cause this code not to run. The correct way to write this code is like this:
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=C:\solutionvs10\test\test\bin\Debug\db2.mdb;**Jet OLEDB:Database Password=secret**")
Try
cn.Open()
''# codes
Finally
cn.Close()
End Try
And there's a short-hand syntax in VB.Net that looks like this:
Using cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=C:\solutionvs10\test\test\bin\Debug\db2.mdb;**Jet OLEDB:Database Password=secret**")
cn.Open()
''# codes
End Using ''# No need to call .Close() any more, the Using structure takes care of it
Now, on to the actual deployment question.
You need to add a setup project to the same solution that holds your application project. You should then be able to use the output of your main project as the package for the setup project and include your initial database file as a content resource. There is no need for anything else included in the setup project; Windows includes the Jet database engine used by access out of the box. You may want to spend some time making sure that the appropriate .Net framework runtime will be installed as a dependency if needed as well.
As Will pointed out including the .mdb file into your project is probably what you are looking for. You can do it in the project manager and then adjusting the properties so that the file is published to the application folder (Copy to Output Directory = Copy Always).
In the code, you should then refer to the database as
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=" & My.Application.Info.DirectoryPath & "\db2.mdb;**Jet OLEDB:Database Password=secret**")
since you don't know the installation path of your database on the client's computer.
On the other side you might want to make sure that you publish your application as a 32bits application since the Jet4.0 does not work for 64bits applications (see http://connect.microsoft.com/VisualStudio/feedback/details/123311/win-xp-x64-jet-v4-0)
For easy install on another computer, I recommend SQLite or SQL Server Compact. Configuration may also be more difficult with access than sqlite or mssql compact.
Beyond that, I would recommend deploying the application using ClickOnce. Documentation here.
I think that making the MDB file part of your project, and setting the right property for it to be copied into the application folder will do the trick.
On the other hand, you will have to make sure you set the MDAC 2.8 as one of your project dependencies so that your users are either informed or required to download and install it to their computers.
I do think you may deploy through ClickOnce, otherwise create a SetUp project, that is doable.