2013-07-26 29 views
0

我想连接到Microsoft Access数据库,但我无法获得连接使用c#连接工作,但无法让它工作试图使用sql连接登录窗体,这也是一个本地连接无法连接到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(); 
     } 
    } 
} 
+2

如果你'赶上(例外EXC){MessageBox中。展(exc.Message); }“这些提供了什么有用的信息? –

+0

@NathanLoding当建立一个到sql server的连接时,我得到一个网络相关或实例特定的错误。 (服务器:命名管道提供程序,错误:40无法建立与SQL服务器的连接) 那是什么?它说我知道我必须做的方式即时通讯它只是不知道什么时间做错了 – user2552211

回答

1

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

的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

+0

这就像一个魅力工作谢谢 – user2552211