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
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.
For MS Access you can use OleDbConnection
with a proper connection string, something like this:
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. Typically it's like Data Source=localhost\\SQLEXPRESS
if your SQL instance is named "SQLEXPRESS" on your local machine. Check out these links:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.