i have a hospital solution in visual studio 2019. i have completed the design, i need to connect to a my access database.
i have this code to try to achieve that
try
{
string constring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Acer\Desktop\Haigazian\Major_Courses\DataBase\My Project\HospitalDB.accdb";
OleDbConnection conDataBase = new OleDbConnection(constring);
String x = textBox1.Text;
OleDbCommand cmdSelectParcel = new OleDbCommand("Select * from Employee where SSN ='" + x + "'", conDataBase);
...
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I also have this at the top of the form using System.Data.OleDb;
however, this isn't being used and is greyed out.
Whenever I write OleDbConnection
it gives me an error and says
"the type name 'OleDbConnection' could not be found in the namespace 'System.Data.OleDb'. this type has been forwarded to assembly 'System.Data.OleDb, Version=4.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' Consider adding a reference to that assembly"
I have copied the code from another solution file and the System.Data.OleDb
works perfectly over there so it must have something to do with my project specifically. I have also tried to add the database access through View>Other Windows>Data Sources but I receive the message
"this window is not supported for the selected project. For steps to enable data binding, please visit: https://aka.ms/WinForms/DataBinding"
and I have checked out the website but I haven't been able to figure out.
Does anyone have any idea how to fix this issue?
You need a reference in your project to System.Data.
Incidentally, once you have that done you need to open the database with..
conDataBase.Open();
You should also parameterize your query rather than passing in values in the query string to avoid SQL Injection...
DataTable Employees = new DataTable();
using (OleDbCommand cmdSelectParcel = new OleDbCommand("Select * from Employee where SSN = ?", conDataBase))
{
cmdSelectParcel.Parameters.Add("?", OleDbType.VarChar).Value = x;
Employees.Load(cmdSelectParcel.ExecuteReader());
}
You'll also need to do something with the data when you get it...
foreach (DataRow Employee in Employees.rows)
{
//Do Something
}
Check that your project actually has a reference to the Microsoft OleDb stuff. eg right click your project in solution explorer and select add->reference->COM then look in the list for your Microsoft OleDB stuff and tick them.
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.