【问题标题】:Cannot Connect to SQL DataBase无法连接到 SQL 数据库
【发布时间】:2013-07-26 08:26:55
【问题描述】:

我正在尝试连接到 Microsoft Access 数据库,但无法使用 c# 进行连接,但无法使用 sql 连接创建登录表单,这也是本地连接

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection("Data Source ='(local)';Initial Catalog ='UserAccounts.accdb';Integrated Security=true");
    SqlDataReader rdr = null;
    try
    {
        conn.Open();
        MessageBox.Show("Working");
    }
    catch (Exception)
    {
        MessageBox.Show("Error with the databse connection");
    }
    finally
    {
        Console.ReadLine();
        if (rdr != null)
        {
            rdr.Close();
        }
        if (conn != null)
        {
            conn.Close();
        }
    }
}

【问题讨论】:

  • 如果你这样做了catch (Exception exc) { MessageBox.Show(exc.Message); },它提供了什么有用的信息?
  • @NathanLoding 我在建立与 sql server 的连接时出现与网络相关或特定于实例的错误。未找到服务器或无法访问服务器。验证实例名称是否正确并且 sql server 配置为允许远程连接。(提供者:命名管道提供者,错误:40 无法打开与 sql server 的连接)就是它所说的我知道我与我称呼它的方式有关,只是不确定我做错了什么

标签: c# login


【解决方案1】:

这听起来很简单,但你说你想连接到 MS Access,但是使用的是专门针对 SQL Server 的SqlConnection,所以它当然永远不会工作。

对于 MS Access,您可以将 OleDbConnection 与适当的连接字符串一起使用,如下所示:

private void button1_Click(object sender, EventArgs e)
{
    string connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=UserAccounts.accdb; Persist Security Info=False;";
    using(OleDbConnection conn = new OleDbConnection(connectionString))
    {
        try
        {
            conn.Open();
            MessageBox.Show("Working");
        }
        catch (Exception e)
        {
            MessageBox.Show("Error with the database connection\n\n + e.ToString()");
        }
    }
    Console.ReadKey(true);
}

检查最合适的连接字符串here

【讨论】:

    【解决方案2】:

    我认为您的Data Source 参数是错误的。如果您的 SQL 实例在本地计算机上命名为“SQLEXPRESS”,则通常类似于Data Source=localhost\SQLEXPRESS。查看这些链接:

    What is the sql connection string I need to use to access localhost\SQLEXPRESS with Windows Authentication or SQL Authentication?

    http://www.connectionstrings.com/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-18
      • 2017-12-22
      • 1970-01-01
      相关资源
      最近更新 更多