无法连接到SQL数据库

时间:2013-07-26 00:01:05

标签: c# login

我正在尝试连接到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();
        }
    }
}

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我认为您的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/

相关问题