How to programmatically attach with server instance through vb.net - sql-server

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.

Related

Long running SP never ends using sqlCommand

I've got a quite expensive stored procedure in my SQL Server database. Launching it from the SQL Server Managment Studio requires some minutes. But I can't launch it via code using SqlCommand.
I've got this code:
spExecQuery = "EXEC [schema].[storedName]"
If I use this vb.NET snippet:
Using sqlCmd As SqlCommand = New SqlCommand(spExecQuery, conn)
sqlCmd.ExecuteNonQuery()
End Using
The script ends with "Timeout expired" error. But if I do:
Using sqlCmd As SqlCommand = New SqlCommand(spExecQuery, conn)
sqlCmd.CommandTimeout = 0
sqlCmd.ExecuteNonQuery()
End Using
The script never ends (it's running from at least 2 hours)... What am I missing? Thank you.
You need to specify first that it's a stored-procedure:
Using sqlCmd As SqlCommand = New SqlCommand(spExecQuery, conn)
sqlCmd.CommandType = CommandType.StoredProcedure
sqlCmd.CommandTimeout = 0
sqlCmd.ExecuteNonQuery()
End Using
You could also use QueueUserWorkItem to let the method run asynchronously, then you don't need to wait until it has finished:
Public Shared Sub ExecuteStoredProcedureAsync()
Threading.ThreadPool.QueueUserWorkItem(
New Threading.WaitCallback(AddressOf ExecuteStoredProcedure)
)
End Sub
Private Shared Sub ExecuteStoredProcedure(threadState As Object)
Dim sw = New Stopwatch()
sw.Start()
Try
' add code or call of long running method here '
Log.WriteInfo(String.Format("ExecuteStoredProcedure(async call) executed successfully, execution-time: {0}.", sw.Elapsed))
Catch ex As Exception
Log.WriteError(String.Format("Exception in ExecuteStoredProcedure (async call), execution-time: {0}.", sw.Elapsed))
End Try
End Sub
It should work if you specify the CmdType.
If still not working, try using the SqlDataReader
cmd.Connection = conn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "proc_name"
Dim dr As SqlDataReader = cmd.ExecuteReader
try to add the command type to your sqlcommand
sqlCmd.CommandType = CommandType.StoredProcedure

Close database connection on SQL Server using ADO .NET

I'm connecting to database using ADO .NET:
Dim conn As SqlConnection
Dim sqlcmd As SqlCommand
Dim da As SqlClient.SqlDataAdapter
Dim table As DataTable
conn = New SqlConnection(Utilities.ConnectionString)
sqlcmd = New SqlClient.SqlCommand()
sqlcmd.Connection = conn
sqlcmd.CommandType = CommandType.StoredProcedure
sqlcmd.CommandText = "mySP"
sqlcmd.Parameters.Add(New SqlClient.SqlParameter("#param", param1))
da = New SqlClient.SqlDataAdapter()
da.SelectCommand = sqlcmd
table = New DataTable()
da.Fill(table)
conn.Close()
sqlcmd.Connection.Close()
That works good.
When I launch on SQL Server the command:
EXEC SP_WHO2
For each call made from the previous code in ADO .NET, I have in the field Command the value: "AWAITING COMMAND", and in the field Status the value is "sleeping".
What does this means? The connection to database is still active? What should I do in order to close db connection?
The fact that after few hours you receive errors about connections exausted means that somewhere in your code you don't dispose correctly of your connection.
The code above seems correct, but what happen if you have exceptions? Are you sure to handle correctly the situation when your code exits unexpectedly from a method, due to exceptions?
The correct approach to this situation is refactoring your code.
Introduce everywhere the Using pattern. So your code above become:
Dim conn As SqlConnection
Dim sqlcmd As SqlCommand
Dim da As SqlClient.SqlDataAdapter
Dim table As DataTable
Using conn = New SqlConnection(Utilities.ConnectionString)
Using sqlcmd = New SqlClient.SqlCommand()
sqlcmd.Connection = conn
sqlcmd.CommandType = CommandType.StoredProcedure
sqlcmd.CommandText = "mySP"
sqlcmd.Parameters.Add(New SqlClient.SqlParameter("#param", param1))
da = New SqlClient.SqlDataAdapter()
da.SelectCommand = sqlcmd
table = New DataTable()
da.Fill(table)
End Using
End Using
This approach will ensure that your disposable objects (connection and command) will be released correctly and you will remove the subtle problem of connection leakings.

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

Connecting to a MS Access database through a function

This is my function:
Public Function DBConnection(ByVal path As String)
' This function makes the database connection and returns the object
' to reference it.
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + path + ";")
cn.Open()
Return cn
End Function
As you can see, I want to initialize a database connection and return it so I can use it in my forms. This function is in a module and my variables are as follows:
Public cn As OleDbConnection
Public cmd As OleDbCommand
Public dr As OleDbDataReader
But I'm not sure how I can use this in my forms, do I just call the function DBConnection and then proceed with my SQL statements? Or do I have to do something else? Help would be very much appreciated, cheers.
Also, I need some opinions. My application relies on a MS Access database. Is it better to initialize the connection on Form_Load and then close the connection when the user closes the program, or open and close the connections as the queries are run? I'm planning to use some database queries on multiple forms hence the reason I was putting it into a module, but I'm not 100% on how I should proceed with this.
Thanks.
From: How to bind Microsoft Access forms to ADO recordsets
Private Sub Form_Open(Cancel As Integer)
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
'Use the ADO connection that Access uses
Set cn = CurrentProject.AccessConnection
'Create an instance of the ADO Recordset class, and
'set its properties
Set rs = New ADODB.Recordset
With rs
Set .ActiveConnection = cn
.Source = "SELECT * FROM Customers"
.LockType = adLockOptimistic
.CursorType = adOpenKeyset
.Open
End With
'Set the form's Recordset property to the ADO recordset
Set Me.Recordset = rs
Set rs = Nothing
Set cn = Nothing
End Sub
A couple things. That function will open a connection every time it's called. You better make sure you are closing the database as well, or that will start eating up memory.
You might look at some other options (such as using NHibernate or another ORM.)
However, if you stay with this model, you could then use the cn that is returned to access your database.

Requested operation requires an OLE DB Session object... - Connecting Excel to SQL server via ADO

I'm attempting to take Excel 2003 and connect it to SQL Server 2000 to run a few dynamicly generated SQL Queries which ultimately filling certain cells.
I'm attempting to do this via VBA via ADO (I've tried 2.8 to 2.0) but I'm getting an error while setting the ActiveConnection variable which is inside the ADODB.Connection object. I need to resolve this pretty quick...
Requested operation requires an OLE DB Session object, which is not supported by the current provider.
I'm honestly not sure what this error means and right now I don't care. How can get this connection to succeed so that I can run my queries?
Here is my VB code:
Dim SQL As String, RetValue As String
SQL = " select top 1 DateTimeValue from SrcTable where x='value' " 'Not the real SQL
RetValue = ""
Dim RS As ADODB.Recordset
Dim Con As New ADODB.Connection
Dim Cmd As New ADODB.Command
Con.ConnectionString = "Provider=sqloledb;DRIVER=SQL Server;Data Source=Server\Instance;Initial Catalog=MyDB_DC;User Id=<UserName>;Password=<Password>;"
Con.CommandTimeout = (60 * 30)
Set Cmd.ActiveConnection = Con ''Error occurs here.
' I'm not sure if the rest is right. I've just coded it. Can't get past the line above.
Cmd.CommandText = SQL
Cmd.CommandType = adCmdText
Con.Open
Set RS = Cmd.Execute()
If Not RS.EOF Then
RetValue = RS(0).Value
Debug.Print "RetValue is: " & RetValue
End If
Con.Close
I imagine something is wrong with the connection string but I've tried over a dozen variations. Now I'm just shooting in the dark....
Note/Update: To make matters more confusing, if I Google for the error quote above, I get a lot of hits back but nothing seems relevant or I'm not sure what information is relevant....
I've got the VBA code in "Sheet1" under "Microsoft Excel Objects." I've done this before but usually put things in a module. Could this make a difference?
You have not opened your connection yet. I think you need a Con.Open before you assign it to the Command object.
Con.ConnectionString = "Provider=sqloledb;DRIVER=SQL Server;Data Source=Server\Instance;Initial Catalog=MyDB_DC;User Id=<UserName>;Password=<Password>;"
Con.CommandTimeout = (60 * 30)
Con.Open
Set Cmd.ActiveConnection = Con 'Error occurs here.
Cmd.CommandText = SQL
Cmd.CommandType = adCmdText

Resources