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

标签 c# sql-server connection

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

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

问题是当时我没有任何其他程序使用数据库。

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

最佳答案

请问,您是如何连接到数据库的? 不要直接打开文件。您需要连接到 SQL Server。

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

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

代码应该是这样的:

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();
        }
    }

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

关于c# - 使用 C# 2010 连接到 SQL Server 2008 的小问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9986236/

相关文章:

c# - C# 中的正则表达式电子邮件验证器中的问题

mysql - 从数据库1中选择*并插入到数据库2中

php - PHP 应用程序中的 MySQL 连接监视器

database - 使用服务名称从 Eclipse 连接到 Oracle Enterprise 11

c# - 从 SQL 获取列中的最后一个单元格

java - 连接到远程数据库

c# - 如何扫描文件并显示当前扫描的详细信息而不使应用程序无响应?

c# - await client.GetStringAsync 无一异常(exception)退出

c# - 使用参数化查询在使用 OldDb 的 Access 中添加比例为 2 的数字类型的列

sql - 表中的每 N 行 LINQ to SQL