使用C#2010连接到SQL Server 2008的小问题

Ign*_*oto 1 c# sql-server connection

我正在尝试将WPF中的应用程序与数据库连接,当我选择数据库时,我希望显示以下消息:

[filename] .mdf目前正在使用中.写一个新名称或关闭使用该文件的其他程序.

问题是我当时没有使用DB的任何其他程序.

谁能告诉我为什么会这样?提前致谢.

Cod*_*ian 5

祈祷,你是如何连接到数据库的?不要直接打开文件.您需要连接到SQL Server.

您需要一个连接字符串,典型的连接字符串如下所示:

Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
Run Code Online (Sandbox Code Playgroud)

代码看起来应该是这样的:

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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

示例来自:http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson02.aspx