Attached DB is not accessible to make connection - sql-server

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")

Related

how to connect VBScript (Excel) to SQL Server web database (via IP)

I'm at my job trying to do some unknow stuff for me, you see, we're trying to connect an excel document with a VBScript Macro to a databse stored in web server but for some reason doesn't recognizes the user and throws an error repeatedly, i discarded a connection issue since it returns an SQL error instead of something like a timeout or server doesn't exists or something like that, we're trying to connect to the server using the ip address, we also checked that the logging method is on mixed (win and sql) and remotes connections to the server are enabled as well, also if i use the credentials provided in the connection string (username and password) i can actually log in to SQL Server without any issue, we also tried a direct connection (external vpn) because we thought it could be our firewall, but got the same error anyway, so we have no clue what it could be and we're kinda running out of ideas on how to do this, i'll post down below the code i'm using to trying the connection (obviously test data but similar to reality)
picture of the error i'm getting (don't post the original since it's in spanish but is very similar to this):
code i'm currently trying:
Sub excel_sqlsrv()
Set rs = CreateObject("ADODB.Recordset")
Set conn = CreateObject("ADODB.Connection")
strConn = "Driver={ODBC Driver 17 for SQL Server};Server=10.20.30.5;Database=mydb;UID=sa;PWD=abcd12345;"
conn.Open strConn
strSqL = "SELECT * FROM USERS"
rs.Open strSqL
End Sub
Any advice, tip or trick could be of tremendous help for me, i'll be looking forward to any kind of comment, thanks in advance
Use the ODBC Data Source Administrator to create a connection named mydb and test it works. Then use
Sub excel_sqlsrv()
Const strConn = "mydb" ' ODBC source
Const strsql = "SELECT * FROM USERS"
Dim conn As Object, rs As Object
Set rs = CreateObject("ADODB.Recordset")
Set conn = CreateObject("ADODB.Connection")
On Error Resume Next
conn.Open strConn
If conn.Errors.Count > 0 Then
Dim i, s
For i = 0 To conn.Errors.Count - 1
s = s & conn.Errors(i) & vbLf
Next
MsgBox s
Else
On Error GoTo 0
Set rs = conn.Execute(strsql)
Sheet1.Range("A1").CopyFromRecordset rs
End If
End Sub
You can try using OLEDB provider instead of ADODB.

Attaching DB after it has been detached

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;"

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;

How to programmatically attach with server instance through vb.net

I need to attach my database, that resided in the MyData directory of my application folder, to the instance of SQL server on client's machine. How to do it?
Could any body give me vb.net code for that so my application does it when run for the first time?
Someone suggested me
Dim cmd As New SqlCommand()
' Dim vrMyConString As String=
Dim conn As System.Data.SqlClient.SqlConnection ' = New SqlConnection(vrMyConString)
cmd.CommandText = "sp_attach_db 'e:\dbTest.mdf', 'e:\dbTest.ldf'"
'conn.connectionstring =
conn.open()
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = conn
cmd.executenonquery()
but on conn.open, it returns error, Object reference not set to an instance of object
Thanks
This works on my Vb.net application.
Make sure sure your connection string: vrMyConString is correct and pointing to your database and with the correct details and it should work
Dim conn As SqlConnection = Nothing
conn = New SqlConnection(vrMyConString )
conn.Open()
You may use ADO.NET provider Linq to SQL or Entity Framework API.

How do I connect to SQL Server with VB?

I'm trying to connect to a SQL server from VB. The SQL server is across the network uses my windows login for authentication.
I can access the server using the following python code:
import odbc
conn = odbc.odbc('SignInspection')
c = conn.cursor()
c.execute("SELECT * FROM list_domain")
c.fetchone()
This code works fine, returning the first result of the SELECT. However, I've been trying to use the SqlClient.SqlConnection in VB, and it fails to connect. I've tried several different connection strings but this is the current code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim conn As New SqlClient.SqlConnection
conn.ConnectionString = "data source=signinspection;initial catalog=signinspection;integrated security=SSPI"
Try
conn.Open()
MessageBox.Show("Sweet Success")
''#Insert some code here, woo
Catch ex As Exception
MessageBox.Show("Failed to connect to data source.")
MessageBox.Show(ex.ToString())
Finally
conn.Close()
End Try
End Sub
It fails miserably, and it gives me an error that says "A network-related or instance-specific error occurred... (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
I'm fairly certain it's my connection string, but nothing I've found has given me any solid examples (server=mySQLServer is not a solid example) of what I need to use.
Thanks!
-Wayne
You are using an ODBC DSN as a SqlClient server name. This is not going to work. You have to use a SqlClient connection string, and for SqlClient the DataSource property is the server name or a SQL Native Client server alias (which is not the same as an ODBC DSN).
Replace signinspection with the actual name of your SQL Server host. If is a named instance or listening on a non default port, you have to specify that too, eg: hostname\instancename
Check out connectionstrings.com for samples. It looks like in your python example, you are accessing the DB via ODBC.
The string you are using is connecting with the built in .NET SQL Server DB provider, so you need to use an ODBC connection string OR change your data source to the actual server name (if no other instances) or servername/instance name.
Sure your Server and Database have the same name?
Here you have a link that would allow you to generate a connection string and test it
http://blogs.msdn.com/dhejo_vanissery/archive/2007/09/07/One-minute-Connection-string.aspx.
Well, I went ahead and used an ODBC Connection. It appears that that is what I was wanting in the first place.
In order to do use the ODBC I had to go to http://support.microsoft.com/kb/310985 and install a few files. Following the directions I came up with the following code that seems to work just fine:
Dim conn As OdbcConnection
conn = New OdbcConnection("DSN=SignInspection")
Dim mystring as String = "SELECT * FROM list_domain"
Dim cmd As OdbcCommand = New OdbcCommand(mystring, conn)
Dim reader As OdbcDataReader
Dim columnCount As Integer
Dim output As String
Dim data as Object() = New Object(10) {}
conn.Open()
MsgBox("Connected!")
reader = cmd.ExecuteReader()
While reader.Read()
columnCount = reader.GetValues(data)
output = ""
For i As Integer = 0 To columnCount - 1
output = output & " " & data(i).ToString()
Next
Debug.WriteLine(output)
End While
conn.Close()
Of course I'll have it cleaned up a lot, but I figure maybe someone will end up looking for the same solution, and maybe they'll see my code before they spend too much time.
ed. columsCount -> columCount
You might want to take a look on Microsoft Enterprise Library Data Access Application Block in order to make it easier to connect and to support multiple underlying datastores.
Good success! =)

Resources