C# 无法连接到SQL数据库
我正在尝试连接到Microsoft Access数据库,但无法使用c#连接,但无法使用sql连接创建登录表单,这也是一个本地连接C# 无法连接到SQL数据库,c#,login,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=tru
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();
}
}
}
我认为您的
数据源
参数是错误的。通常,如果本地计算机上的SQL实例名为“SQLEXPRESS”,则类似于Data Source=localhost\SQLEXPRESS
。查看以下链接:
听起来可能很简单,但您说您想连接到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);
}
如果执行以下操作,请选中最合适的连接字符串,
catch(Exception exc){MessageBox.Show(exc.Message);}
这提供了哪些有用的信息?@NathanLoding我发现在建立与sql server的连接时发生了与网络相关或特定于实例的错误。服务器找不到或不可访问。请验证实例名称是否正确,以及sql server是否配置为允许远程连接。(提供程序:命名管道提供程序,错误:40无法选择与sql server的连接)这就是它所说的我知道我与我调用它的方式有关,只是不确定ime做错了什么