简体   繁体   中英

Little issue connecting to SQL Server 2008 with C# 2010

I'm trying to connect an application in WPF with a database and when I select the database I want this message is shown:

[filename].mdf is currently in use. Write a new name or close the other program that's using the file.

The problem is that I don't have any other program using the DB at that time.

Can anyone tell me why is this happening? Thanks in advance.

How, pray, are you connecting to the database? Do not open the file directly. You need to connect to SQL Server.

You need a connection string, a typical connection string looks like this:

Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

The code should look something like this:

SqlConnection conn = new SqlConnection(
        "Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");

    SqlDataReader rdr = null;

    try
    {
        // 2. Open the connection
        conn.Open();

        // 3. Pass the connection to a command object
        SqlCommand cmd = new SqlCommand("select * from Customers", conn);

        //
        // 4. Use the connection
        //

        // get query results
        rdr = cmd.ExecuteReader();

        // print the CustomerID of each record
        while (rdr.Read())
        {
            Console.WriteLine(rdr[0]);
        }
    }
    finally
    {
        // close the reader
        if (rdr != null)
        {
            rdr.Close();
        }

        // 5. Close the connection
        if (conn != null)
        {
            conn.Close();
        }
    }

Example from: http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson02.aspx

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