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()
Related
I'm quite confused why the data that I added was not saved to the database.
While my program is running there are no problems in updating the data that is shown in DataGridView but when I close the program, the added data disappears.
I tried to show table data but there were no new data added. Can you tell me what is the problem?
This is my code:
Dim con As New SqlClient.SqlConnection
Dim cmd As New SqlClient.SqlCommand
Dim adaptor As New SqlClient.SqlDataAdapter
Dim dataset As New DataSet
con.ConnectionString = ("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True")
con.Open()
cmd.CommandText = "INSERT INTO [Table](FirstName,LastName,MI,Address,Email) VALUES(#FN,#LN,#MI,#AD,#EM)"
cmd.Connection = con
cmd.Parameters.Add("#FN", SqlDbType.VarChar).Value = TextBox1.Text
cmd.Parameters.Add("#LN", SqlDbType.VarChar).Value = TextBox2.Text
cmd.Parameters.Add("#MI", SqlDbType.VarChar).Value = TextBox3.Text
cmd.Parameters.Add("#AD", SqlDbType.VarChar).Value = TextBox4.Text
cmd.Parameters.Add("#EM", SqlDbType.VarChar).Value = TextBox5.Text
cmd.ExecuteNonQuery()
MsgBox("Added!")
con.Close()
Me.TableTableAdapter.Fill(Me.Database1DataSet.Table)
The whole AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to create your database on the server using a management tool (like SSMS Express), give it a logical name (e.g. MyDatabase), and then connect to it using its logical database name (given when you create it on the server). Don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=MyDatabase;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Betrand's blog post Bad Habits to Kick - using AttachDbFileName for more background info
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.
I have been searching for a couple hours, and found several questions, but none of them really explained this in a way I can understand.
I'm programming a game similar to Rock Paper Sissors, except with many more selections, and the possiblity of a tie. I had originally hardcoded all of the possible outcomes, then decided to try a database so I can learn and practice sql as well.
Problem is, I can't figure out for the life of me how to connect to my local database, now that I have set it up and filled it through Visual Studio 2010. I can connect to it through Server Explorer just fine, and I can see it in Solution Explorer. I've tried several things, along the lines of:
Private sqlConn As New SqlConnection("Data Source=(local)|DataDirectory|\Outcomes.sdf;database=Outcomes;Integrated Security=true")
Private sqlConn As New SqlConnection("Data Source=.\SQLEXPRESS; Integrated Security=true")
Dim sqlConn As SqlConnection
sqlConn = New SqlConnection("DataSource=..\..\Outcomes.sdf")
I am relatively new to sql, but know enough through tinkering to build a sql statement and get me the result I want. But I've never connected to a database before. I've looked on MSDN and tried several things I saw on there (everything that looked like what I needed, really) but it still hasn't worked.
If I can connect, I already have my statement set, and have tested it through the database itself. Any help would be wonderful, especially if it's explained in a way I can understand it and use it for later.
Also, if it helps and isn't noticed through my tried code, my db name is Outcomes. I don't know if that is needed or will help, but just in case.
Please visit connection strings here...
It also would have been helpful to know what type of DBMS you are using as well. I noticed you have an .sdf database file, not a DBMS (For ex: MySql, SQL or Oracle). Therefore, your connection string is really going to depend on what you want.
Your issue is here by the way...
Private sqlConn As New SqlConnection("Data Source=(local)|DataDirectory|\Outcomes.sdf;database=Outcomes;Integrated Security=true")
*You cant use the SqlConnection you have because its not supported with the use of .sdf files.
Instead you have to use: System.Data.SqlServerCe 'This is for compact edition
If you would like to know more about this please see here.
Kendra,
Here are the logical Steps you will need to follow to access the database programmatically:
Note: I'm assumming you have the proper SQLExpress | SQL Server Database setup whether local or remote the methods below are identical except for the connection string information.
1) Import the Sql AdoNet Namespace so you can use the proper SQL Server Client Objects & Methods;
a) Imports System.Data.SqlClient
2) Establish a Connection to the database with the ADO Connection Object:
' Create your ADO Connection Object:
Private myConn As SqlConnection
myConn = New SqlConnection("Initial Catalog=OutComes;" & _
"Data Source=localhost;Integrated Security=SSPI;")
Note: This connection string uses integrated security from your windows machine. you could also use standard security where you would need to enter your username and password credentials. Its your choice.
3) Setup Your ADO Command Object to Define your data retrieval query:
'Create a Command object.
Private myCmd As SqlCommand
myCmd = myConn.CreateCommand
myCmd.CommandText = "SELECT FirstName, LastName FROM Employees"
'Open the connection.
myConn.Open()
Note: Subsitute CommandText string for your actual query based upon your own database schema.
4) Read, Fetch, Display Data using the SQLDataReader Object:
Private results As String
Private myReader As SqlDataReader
myReader = myCmd.ExecuteReader()
'Traverse the DataSet and Display in GUi for Example:
Do While myReader.Read()
results = results & myReader.GetString(0) & vbTab & _
myReader.GetString(1) & vbLf
Loop
'Display results.
MsgBox(results)
5) Gracefully Close all Objects Used:
' Close the reader and the database connection.
myReader.Close()
myConn.Close()
Note - You'll need to consult microsoft for further connection string formats, since I don't have enough info. But this should clarify the actual big picture steps for you.
Regards,
Scott
Hey all i am VERY new to a Oracle DB and i am trying to connect to it via VB.net 2010. I have been trying the following:
Dim myConnection As OleDbConnection
Dim myCommand As OleDbCommand
Dim dr As OleDbDataReader
myConnection = New OleDbConnection("Provider=MSDAORA.1;UserID=xxxx;password=xxxx; database=xxxx")
'MSDORA is the provider when working with Oracle
Try
myConnection.Open()
'opening the connection
myCommand = New OleDbCommand("Select * from emp", myConnection)
'executing the command and assigning it to connection
dr = myCommand.ExecuteReader()
While dr.Read()
'reading from the datareader
MessageBox.Show("EmpNo" & dr(0))
MessageBox.Show("EName" & dr(1))
MessageBox.Show("Job" & dr(2))
MessageBox.Show("Mgr" & dr(3))
MessageBox.Show("HireDate" & dr(4))
'displaying data from the table
End While
dr.Close()
myConnection.Close()
Catch ee As Exception
End Try
And i get the error on the Catch ee As Exception line: ORA-12560: TNS:protocol adapter error
I also have a tnsnames.ora file on my computer but i am unsure if i need to use that when connecting (or really, how too in the first place)? Is it needed for the code above?
I am trying to use a DNS-Less connection to the DB. Not sure if that is what it is doing in this or not?
Any help would be great!!! :o)
David
There are many ways: the one I use almost every time that doesn't require an entry in TNSNAMES.ORA is this:
Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)));User Id=myUsername;Password=myPassword;
And if you don't need an OleDb connection I think you should use System.Data.OracleClient or any other free provider (like DevArt dotConnect for Oracle Express)
Source: http://www.connectionstrings.com/oracle
I always use www.connectionstrings.com/ when I need to create a new connection string to the DB and when connection string format is not on top of my head.
I've succesfully synchronized both source and local db using the local database cache item in VS 2008.
However, I need to access the SQL CE db directly from within another dll/process, and without using a dataset. The reason being that my business object code does not use datasets.
The final code wouldlook something like this:
Dim conn As New SqlServerCe.SqlCeConnection("Data Source=C:\Development\UserDirectory\UserDirectory.DBSyncher\ProfDir.sdf;Persist Security Info=False;")
Dim cmd As New SqlServerCe.SqlCeCommand("Select EmailAddress from Employees Where ID=23", conn)
Dim returnString As String = ""
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
returnString = cmd.ExecuteScalar
conn.Close()
cmd = Nothing
I notice something very strange using a dataset the synchronized changes are shown but accessing the CE database file directly returns old data - no synched data whatsoever.
What am I missing? Any help would be greatly appreciated.
Figured it out!
Forgot that CE is in process, thus it copies the database file(.sdf) to the Debug folder. You have to to reference that database not the one in your project. DOH!