简体   繁体   中英

Establishing connection with local SQL Server database file

I am trying to set up connection with a SQL Server database file AdventureWorksDW2008R2_Data.mdf located on my D drive.

I have used connection string :

Server=.\SQLExpress;AttachDbFilename=D:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\AdventureWorksDW2008R2_Data.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True;"

However, I cannot establish connection.

I aim to retrieve the number of employees in a particular department from the database (tables employee and department are present in the db).

Can anyone highlight or suggest steps that would allow me do that?

use following code to connect:

public static void Main()
        {
            try
            {
                string connectString =
                    "Server=IRIS-CSG-108\\SQLEXPRESS;" +
                    "Integrated Security=true";
                SqlConnectionStringBuilder builder =
                    new SqlConnectionStringBuilder(connectString);
                Console.WriteLine("Original: " + builder.ConnectionString);
                Console.WriteLine("AttachDBFileName={0}", builder.AttachDBFilename);

                builder.AttachDBFilename = @"E:\\TCMS.mdf";
                Console.WriteLine("Modified: " + builder.ConnectionString);

                using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
                {
                    connection.Open();
                    // Now use the open connection.
                    Console.WriteLine("Database = " + connection.Database);

                    DataSet ds = new DataSet();
                    SqlDataAdapter da = new SqlDataAdapter("Select * from mytable", connection);
                    da.Fill(ds);
                }
                Console.WriteLine("Press any key to finish.");
                Console.ReadLine();


            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

If you are using the sample DataBase from your Sql Server Management Studio, then i will not work. Close your Sql Management Studio if you are working..

将mdf文件添加到d:\\中的新文件夹中,然后尝试以下操作:Data Source =。\\ SQLEXPRESS; AttachDbFileName = d:\\ data \\ Customers.mdf; Integrated Security = True; User Instance = True可能存在读取问题路径。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM