Attaching DB after it has been detached - sql-server

I am using following code to attach my database to SQL Server. The problem is if I create a new file and attach it through my code but when I detach the file using SSMS and again run the same code, it gives error.
Error is:
Unable to open the physical file "e:\dbForATTWithPWD.mdf". Operating
system error 2: "2(error not found)"
The code is:
Dim conn As New SqlConnection("Server=MyHomeServer\SQLExpress;Database=master;Integrated Security=SSPI")
Dim cmd As New SqlCommand("", conn)
cmd.CommandText = "CREATE DATABASE MyHomeWithPWD ON ( FILENAME = 'e:\dbForATTWithPWD.mdf' ), ( FILENAME = 'e:\dbForATTWithPWD_log.ldf' ) FOR ATTACH"
conn.Open()
cmd.ExecuteNonQuery()
cmd.Dispose()
conn.Dispose()
Why is it happening. All the permissions are the same even first time.
Also what should be the connection string if I need to use DB with uid sa and pwd abc123 ?
Thanks

Try to making sure that nothing else is accessing that mdb file after you detach it. I would probably shutdown that SQLServer instance and restart. Also, I'd make sure that you could detach and reattach in SSMS.
For your connection string try this: "Server=YOURSVR;Database=DB;Trusted_Connection=False;User ID=sa;Password=abc123;"

Related

Vb.Net & SQL Server Express : Create User for login throws error

We attached the database PStorage to the server.
Then I tried to create the login & user using the following code:
Dim con As New SqlConnection
Dim query As SqlCommand
con.ConnectionString = "Server=(LocalHost);Data Source=LocalHost\SQLEXPRESS;Database=PSTORAGE;Integrated Security=TRUE"
con.Open()
query.CommandText = "IF NOT EXISTS(SELECT [LoginName] FROM MASTER.DBO.SYSLOGINS WHERE [Name]='UserCP') CREATE LOGIN UserCP WITH PASSWORD='CPPassword'"
query.ExecuteNonQuery()
query.Dispose()
query.CommandText = "IF NOT EXISTS(SELECT [Name] FROM SYS.DATABASE_PRINCIPALS WHERE [Name]='CPUser') CREATE USER CPUser FOR LOGIN UserCP"
query.ExecuteNonQuery() 'This line is throwing the error -> Login Failed for the User 'UserCP'.
query.Dispose()
The error we are getting after executing the second query is
Login failed for the user 'UserCP'
While attaching the database the same error occurs. Then we had to use sqlCmd.
In all the systems this method works fine. But in one of our customers system this problem occurs. What might be the reason?
After a lot of tries we could come to know that the folder was compressed [All the file names were in blue colour]. Since the database files were inside the compressed folder- none of the operations could be done on them perfectly.
Right click on the database folder, Press on Properties
Press on Advanced
Untick the Compress contents to save disk space
Save the changes made

SQL Server : Backup Error

When we are trying to backup our database we get an error.
Front End : VB.Net
Back End : SQL Server
DB Name : PROFITSTORAGE
Backup Location : 'D:\Profit\Data\ProfitStorage.Bak'
Code:
Dim con As New SqlConnection
Dim query As SqlCommand
Try
con.ConnectionString = "Server=(LocalHost);Data Source=LocalHost\SQLEXPRESS;Integrated Security=SSPI"
con.Open()
query = con.CreateCommand
query.CommandText = "BACKUP DATABASE PROFITSTORAGE TO DISK='D:\Profit\Data\ProfitStorage.bak' WITH INIT"
query.ExecuteNonQuery()
query.Dispose()
con.Close()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Backup Failed")
End Try
Query used :
BACKUP DATABASE PROFITSTORAGE
TO DISK='D:\Profit\Data\ProfitStorage.bak' WITH INIT
Error Message :
Cannot open backup device 'D:\Profit\Data\ProfitStorage.bak'. Operating system error 3 (failed to retrieve text for this error. Reason: 15105).
BACKUP DATABASE is terminating abnormally.
How to sort out this issue?
The query is not creating the folder if its not existing.
We should create a folder manually instead.
Since we are using VB.Net we had to create a folder with the following code before backup:
My.Computer.FileSystem.CreateDirectory("D:\Profit\Data\")

Creating a SQL Server database for the first time at run time

I want to create a SQL Server database at runtime in my vb.net project. I know how to actually code the database but I am wondering where should I actually put the code? Should I be putting the code in the start up form or should it go into a class on it's own? Also, this project will be going on more than one pc at a particular site, so I only want the database to be created the first time the project is activated and then just be able query the database on different pcs after that. How do I do this? All help on this matter would be greatly appreciated.
EDIT:
Ok, so I should have been clearer on this. The project is going to be on 2 different pcs, it is for visitors entering a business. The pcs will be in reception and security. I need both pcs to access the same database with the same details in it. I don't want to have two different databases where details have to be put in twice. For example, if I enter at reception today and then go through security tomorrow, then all I should have to enter in security is why I'm entering the business again, I shouldn't have to put my details in a second time. How do I go about this? As I already said, I know how to code the database, but I want to know how to do what I stated in my question.
Thanks in advance for all help given.
If you add the code in module or in form load then it will execute all the time when the form loads. it is wasting of time to check whether the database exist or not in each run. So it is better to place a button with text "Create database" for this purpose(or menu item). it's click event will load the database. the following code can be used to create the database dynamically on button click
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'creating and initializing the connection string
Dim myConnectionString As SqlConnection = New SqlConnection("Data Source=(local)\SQLEXPRESS;Initial Catalog=master;Integrated Security=True;Pooling=False")
'since we need to create a new database set the Initial Catalog as Master
'Which means we are creating database under master DB
Dim myCommand As String //to store the sql command to be executed
myCommand = "CREATE database my_db" //the command that creates new database
Dim cmd As SqlCommand = New SqlCommand(myCommand, myConnectionString) // creating command for execution
Try
cmd.Connection.Open() //open a connection with cmd
cmd.ExecuteNonQuery() //Execute the query
cmd.Connection.Close() //Close the connection
Catch
MsgBox(" Already installed database", MsgBoxStyle.Critical, " MaS InfoTech- Warning")
End Try
'Creating table to the dynamicaly created database
Try
Dim cn As SqlConnection = New SqlConnection("Data Source=(local)\SQLEXPRESS;Initial Catalog=my_db;Integrated Security=True;Pooling=False")
'here the connection string is initialized with Initial Catalog as my_db
Dim sql As String //sql query string
sql = "CREATE TABLE customer(cus_name varchar(50) NULL,address varchar(50) NULL,mobno numeric(18, 0) NULL,tin varchar(50) NULL,kg varchar(50) NULL)"
cmd = New SqlCommand(sql, cn) // create command with connection and query string
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
Catch
MsgBox(" Already existing table", MsgBoxStyle.Critical, " MaS InfoTech- Warning")
End Try
End Sub

Concept of creating or attaching database to the instance of SQL Server

I have a SQL Server database which I can attach manually using SSMS and application works fine after this. I want to make the process automatic, i.e do not want my clients to use SSMS to attach database, but I want my application to do it at first time run or during installation.
But I have no idea at all how to do it. Many people suggested code snippets but I do not know where to put them.
I have seen a concept of SQLDMO but could not find over google how to make and use them in vb.net.
Could any body give me some help on it?
After getting hint, I tried following code in vb.net
Dim conn As New SqlConnection("Server=(local);Data Source=;Integrated Security=SSPI")
Dim cmd As New SqlCommand("", conn)
cmd.CommandText = "CREATE DATABASE MyDBTest ON ( FILENAME = 'D:\dbSQLTest.mdf' ), ( FILENAME = 'D:\dbSQLTest_log.ldf' ) FOR ATTACH"
conn.Open()
cmd.ExecuteNonQuery()
cmd.Dispose()
conn.Dispose()
When executed, it returns error
Unable to open the physical file "D:.Net Programs\AttachDBProg\AttachDBProg\dbSQLTest.mdf". Operating system error 5: "5(failed to retrieve text for this error. Reason: 15105)".
Please help.
Thanks
You can use FOR ATTACH one you have connected to the server for the 1st time by executing:
CREATE DATABASE XXX ON ( FILENAME = N'blah.mdf' ), ( FILENAME = N'blah.ldf' ) FOR ATTACH;

Attached DB is not accessible to make connection

I created a DB using following code.
Dim conn As New SqlConnection("Server=.\SQLExpress;Data Source=;Integrated Security=SSPI")
Dim cmd As New SqlCommand("", conn)
cmd.CommandText = "CREATE DATABASE MyDBTest22 ON ( FILENAME = 'D:\dbTestATTTTTTT.mdf' ), ( FILENAME = 'D:\dbTestATTTTTTT_log.ldf' ) FOR ATTACH"
conn.Open()
cmd.ExecuteNonQuery()
cmd.Dispose()
conn.Dispose()
It ran without any error but when I opened SSMS, I could not see my file attached to the server. Also, I tried to make a connection, but it says file does not exist but when I tried to re-run the above code, it says File already exists.
Something wrong with my way of doing it? I want to see it attached with the instance of my SQL Server Express 2005, using SSMS.
Thanks
You're missing a database to connect to in your connection string - if you want to attach a file, I would recommend connecting to the master database:
Dim conn As New SqlConnection("Server=.\SQLExpress;Database=master;Integrated Security=SSPI")

Resources