Attach sql mdf file in code

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • redhat37
    New Member
    • Mar 2009
    • 3

    Attach sql mdf file in code

    How do i attach a sql express .mdf file which is located in a certain folder on my C: drive to sql express in my code, there are many examples on the web but none of them seem to give a code example which works, I am using visual Studio 2008 and Sql Express 2005
  • MrMancunian
    Recognized Expert Contributor
    • Jul 2008
    • 569

    #2
    I think this should work:

    Code:
    dim cnnConnection As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\database.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True")
    Of course you'll need to have SQL Express installed.

    Steven

    Comment

    • aryanbs
      New Member
      • Mar 2009
      • 42

      #3
      Here is a good repository of connection strings

      Connection strings for SQL Server 2005. Connect using ODBC Driver 11 for SQL Server, Microsoft.Data.SqlClient, SqlConnection, SQLNCLI11 OLEDB.

      Comment

      • redhat37
        New Member
        • Mar 2009
        • 3

        #4
        Database Attach

        Thanks, that works, but it does not persist the attachment in sql manager,
        Code:
                    Dim cnnConnection As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=" & Application.StartupPath + "\datafiles\" + TextBox1.Text + ".mdf" & ";Integrated Security=True;Connect Timeout=30;User Instance=True")
        Is it possible to keep this file attached after the program has exited
        Last edited by Frinavale; Apr 14 '09, 04:10 PM. Reason: Added code tags. Please post code snippets in [code] [/code] tags.

        Comment

        • redhat37
          New Member
          • Mar 2009
          • 3

          #5
          I got it to work, thanks for all the excellent help, this is the solution
          Code:
                          Dim cnnConnection As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=" & Application.StartupPath + "\datafiles\" + TextBox1.Text + ".mdf" & ";Integrated Security=True;Database='" & TextBox1.Text & "';Connect Timeout=30")
                          cnnConnection.Open()
                          cnnConnection.Close()
          Last edited by Frinavale; Apr 14 '09, 04:10 PM. Reason: Added code tags. Please post code snippets in [code] [/code] tags.

          Comment

          Working...