[英]Cannot Connect to SQL DataBase
I'm trying to connect to a Microsoft Access database but i can't get the connection to work using c# to connect but can't get it to work trying to making a login form using sql connection, this is also a local connection 我正在尝试连接到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();
}
}
}
It may sound so simple, but you said you want to connect to MS Access , but are using SqlConnection
, which is specifically to SQL Server, so of course it will never work. 听起来似乎很简单,但是您说过您想连接到MS Access ,但是正在使用
SqlConnection
,它专门用于SQL Server,因此,它永远不会起作用。
For MS Access you can use OleDbConnection
with a proper connection string, something like this: 对于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);
}
Check the most appropriate connection string here 在这里检查最合适的连接字符串
Your Data Source
parameter is wrong, I think. 我认为您的
Data Source
参数是错误的。 Typically it's like Data Source=localhost\\SQLEXPRESS
if your SQL instance is named "SQLEXPRESS" on your local machine. 如果您的SQL实例在本地计算机上被命名为“ SQLEXPRESS”,则通常类似于
Data Source=localhost\\SQLEXPRESS
。 Check out these links: 查看以下链接:
What is the sql connection string I need to use to access localhost\\SQLEXPRESS with Windows Authentication or SQL Authentication? 使用Windows身份验证或SQL身份验证访问localhost \\ SQLEXPRESS时需要使用什么sql连接字符串?
http://www.connectionstrings.com/ http://www.connectionstrings.com/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.