Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. Visual Basic
  4. Disconnecting from SqlServer Database from VB.net

Disconnecting from SqlServer Database from VB.net

Scheduled Pinned Locked Moved Visual Basic
databasecsharpsharepointhelp
12 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • E Offline
    E Offline
    edmonson
    wrote on last edited by
    #1

    Hello, I'am developing an App that needs to access a SqlDataBase named "Work", but this may be located in any drive of my system (C:,D:,U:,...). The database structure is always the same, so I use a unique name and only change the files. When the application start, I use a OpenFileDialog to locate the database and execute an storedprocedure to attach the database to SqlServer (EXEC sp_attach_db @dbname ...). This works fine, and I can work with the database. When the user ends to work with database, I want to detach ("EXEC sp_detach_db) this from my App to allow to choose another location one. At this point I get an error reporting that the database is currently in use, ans so, it can't be detached. StoredProcedures form attach and detach owns to Master database, so when I execute it I'am not using my database. Do you know any procedure to disconnect my App from database using system.data, and then I could execute the detach procedure ? (If I only execute Attach and Detach, without accessing to database, is runs fine). Here the Detach function:

    Public Function DetachDB(ByVal DbName As String) As Boolean
    Dim Cmd As New SqlClient.SqlCommand
    Dim AffectedRows As Int32
    Dim TmpDbName As String = _DbName
    _DbName = "Master"
    Cmd.Connection = GetConnection
    Cmd.CommandText = "EXEC sp_detach_db @dbname = '" & DbName & "'"
    Cmd.CommandType = CommandType.Text
    Cmd.Connection.Open()
    Try
    AffectedRows = Cmd.ExecuteNonQuery()
    Cmd.Connection.Close()
    _DbName = TmpDbName
    Return (True)
    Catch e As Exception
    If PopupErrors Then
    MessageBox.Show("[DB]Error separando la base de datos " + e.Message)
    End If
    Cmd.Connection.Close()
    _DbName = TmpDbName
    Return False
    Exit Function
    End Try
    End Function

    L 1 Reply Last reply
    0
    • E edmonson

      Hello, I'am developing an App that needs to access a SqlDataBase named "Work", but this may be located in any drive of my system (C:,D:,U:,...). The database structure is always the same, so I use a unique name and only change the files. When the application start, I use a OpenFileDialog to locate the database and execute an storedprocedure to attach the database to SqlServer (EXEC sp_attach_db @dbname ...). This works fine, and I can work with the database. When the user ends to work with database, I want to detach ("EXEC sp_detach_db) this from my App to allow to choose another location one. At this point I get an error reporting that the database is currently in use, ans so, it can't be detached. StoredProcedures form attach and detach owns to Master database, so when I execute it I'am not using my database. Do you know any procedure to disconnect my App from database using system.data, and then I could execute the detach procedure ? (If I only execute Attach and Detach, without accessing to database, is runs fine). Here the Detach function:

      Public Function DetachDB(ByVal DbName As String) As Boolean
      Dim Cmd As New SqlClient.SqlCommand
      Dim AffectedRows As Int32
      Dim TmpDbName As String = _DbName
      _DbName = "Master"
      Cmd.Connection = GetConnection
      Cmd.CommandText = "EXEC sp_detach_db @dbname = '" & DbName & "'"
      Cmd.CommandType = CommandType.Text
      Cmd.Connection.Open()
      Try
      AffectedRows = Cmd.ExecuteNonQuery()
      Cmd.Connection.Close()
      _DbName = TmpDbName
      Return (True)
      Catch e As Exception
      If PopupErrors Then
      MessageBox.Show("[DB]Error separando la base de datos " + e.Message)
      End If
      Cmd.Connection.Close()
      _DbName = TmpDbName
      Return False
      Exit Function
      End Try
      End Function

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      How does your connection-string look? Do you connect to the "master" database on the server, or to your named database?

      I are Troll :suss:

      E 1 Reply Last reply
      0
      • L Lost User

        How does your connection-string look? Do you connect to the "master" database on the server, or to your named database?

        I are Troll :suss:

        E Offline
        E Offline
        edmonson
        wrote on last edited by
        #3

        The connection to the app database is:

        "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=work;Data Source=pcjordi2009\sqlexpress"

        And when I connect to detach/attach I use:

        "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Master;Data Source=pcjordi2009\sqlexpress"

        L 1 Reply Last reply
        0
        • E edmonson

          The connection to the app database is:

          "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=work;Data Source=pcjordi2009\sqlexpress"

          And when I connect to detach/attach I use:

          "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Master;Data Source=pcjordi2009\sqlexpress"

          L Offline
          L Offline
          Lost User
          wrote on last edited by
          #4

          Looks good. Just tried from SQL Management Studio, one can simulate an open connection by simply opening a table in edit-mode.

          ALTER DATABASE [AdventureWorks] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
          GO
          USE master;
          GO
          sp_detach_db 'AdventureWorks';

          The first command sets the database to single-user mode, effectively disconnecting everyone else :)

          I are Troll :suss:

          E 1 Reply Last reply
          0
          • L Lost User

            Looks good. Just tried from SQL Management Studio, one can simulate an open connection by simply opening a table in edit-mode.

            ALTER DATABASE [AdventureWorks] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
            GO
            USE master;
            GO
            sp_detach_db 'AdventureWorks';

            The first command sets the database to single-user mode, effectively disconnecting everyone else :)

            I are Troll :suss:

            E Offline
            E Offline
            edmonson
            wrote on last edited by
            #5

            I've tested from Management Studio and it works properly. From my application, the problem continues. When I execute ALTER DATABASE... the DB enters in Single User Mode (An icon appears on Db List in Mabagement Studio, but when execute detach it fails reporting that Database is in use :(

            L 1 Reply Last reply
            0
            • E edmonson

              I've tested from Management Studio and it works properly. From my application, the problem continues. When I execute ALTER DATABASE... the DB enters in Single User Mode (An icon appears on Db List in Mabagement Studio, but when execute detach it fails reporting that Database is in use :(

              L Offline
              L Offline
              Lost User
              wrote on last edited by
              #6

              edmonson wrote:

              When I execute ALTER DATABASE... the DB enters in Single User Mode (An icon appears on Db List in Mabagement Studio, but when execute detach it fails reporting that Database is in use :(

              Strange.. Can you post the offending code here? I've tried it here this way, just to verify that it's actually possible;

              string cs = "Server=.\\SQLEXPRESS;Database=master;Trusted_Connection=True;";
              using (var con = new SqlConnection(cs))
              using (var cmd = new SqlCommand())
              {
              con.Open();
              cmd.Connection = con;
              cmd.CommandText = @"ALTER DATABASE [AdventureWorks] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;";
              cmd.ExecuteNonQuery();
              cmd.CommandText = @"sp_detach_db 'AdventureWorks';";
              cmd.ExecuteNonQuery();
              }

              I are Troll :suss:

              E 1 Reply Last reply
              0
              • L Lost User

                edmonson wrote:

                When I execute ALTER DATABASE... the DB enters in Single User Mode (An icon appears on Db List in Mabagement Studio, but when execute detach it fails reporting that Database is in use :(

                Strange.. Can you post the offending code here? I've tried it here this way, just to verify that it's actually possible;

                string cs = "Server=.\\SQLEXPRESS;Database=master;Trusted_Connection=True;";
                using (var con = new SqlConnection(cs))
                using (var cmd = new SqlCommand())
                {
                con.Open();
                cmd.Connection = con;
                cmd.CommandText = @"ALTER DATABASE [AdventureWorks] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;";
                cmd.ExecuteNonQuery();
                cmd.CommandText = @"sp_detach_db 'AdventureWorks';";
                cmd.ExecuteNonQuery();
                }

                I are Troll :suss:

                E Offline
                E Offline
                edmonson
                wrote on last edited by
                #7

                Sure, this code works and the database is deatached succesful! but when I execute an attach again: - Database is attached successful (I can see on Management Studio) - I open a connection an it opens succesful. - But when I call an cmd.ExecuteReader to get data, then next error message appears: "Error at level transport when send the query to the server. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe)" I've reviewed SQL configuration, and all seems good. If I restart the App all work succesful. Any idea, why the server process stopped ??

                L 1 Reply Last reply
                0
                • E edmonson

                  Sure, this code works and the database is deatached succesful! but when I execute an attach again: - Database is attached successful (I can see on Management Studio) - I open a connection an it opens succesful. - But when I call an cmd.ExecuteReader to get data, then next error message appears: "Error at level transport when send the query to the server. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe)" I've reviewed SQL configuration, and all seems good. If I restart the App all work succesful. Any idea, why the server process stopped ??

                  L Offline
                  L Offline
                  Lost User
                  wrote on last edited by
                  #8

                  edmonson wrote:

                  Any idea, why the server process stopped ??

                  Alas, no. Is it replicatable?

                  I are Troll :suss:

                  E 2 Replies Last reply
                  0
                  • L Lost User

                    edmonson wrote:

                    Any idea, why the server process stopped ??

                    Alas, no. Is it replicatable?

                    I are Troll :suss:

                    E Offline
                    E Offline
                    edmonson
                    wrote on last edited by
                    #9

                    Sorry, the message was: Sure, your code works and the database is deatached succesful! but when I execute an attach again(the same database): - Database is attached successful (I can see on Management Studio) - I open a connection an it opens succesful. - But when I call an cmd.ExecuteReader to get data, then next error message appears: "Error at level transport when send the query to the server. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe)" I've reviewed SQL configuration, and all seems good. If I restart the App all work succesful. Any idea about it ?

                    L 1 Reply Last reply
                    0
                    • E edmonson

                      Sorry, the message was: Sure, your code works and the database is deatached succesful! but when I execute an attach again(the same database): - Database is attached successful (I can see on Management Studio) - I open a connection an it opens succesful. - But when I call an cmd.ExecuteReader to get data, then next error message appears: "Error at level transport when send the query to the server. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe)" I've reviewed SQL configuration, and all seems good. If I restart the App all work succesful. Any idea about it ?

                      L Offline
                      L Offline
                      Lost User
                      wrote on last edited by
                      #10

                      I don't know; does it happen every time after a reattach?

                      I are Troll :suss:

                      1 Reply Last reply
                      0
                      • L Lost User

                        edmonson wrote:

                        Any idea, why the server process stopped ??

                        Alas, no. Is it replicatable?

                        I are Troll :suss:

                        E Offline
                        E Offline
                        edmonson
                        wrote on last edited by
                        #11

                        Yes, every time I attached again (without exiting from application) and try to get data, the problem appears. But if I restart application and reattach then works fine ! (Strange behavior:-() If I find the solution I'll report it.

                        L 1 Reply Last reply
                        0
                        • E edmonson

                          Yes, every time I attached again (without exiting from application) and try to get data, the problem appears. But if I restart application and reattach then works fine ! (Strange behavior:-() If I find the solution I'll report it.

                          L Offline
                          L Offline
                          Lost User
                          wrote on last edited by
                          #12

                          edmonson wrote:

                          Yes, every time I attached again (without exiting from application) and try to get data, the problem appears.

                          Without exiting from the application; so something gets left behind, in either the application or SQL Server. When the application starts to fetch data, then the application will create a new Connection object, right? Thinking out loud; the database is re-attached, from within the application. Could it be that we disconnected an active DataReader during the detaching?

                          I are Troll :suss:

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups