How to create database table class - c#

I have a project in c# about a hospital system which contains 30 child forms.
I have created database which contain more than 30 tables.
I created data access like this:
namespace emamTree
{
public class DBAccess
{
public static string connectionString = ConfigurationManager.ConnectionStrings["TreeFinal"].ConnectionString ;
public SqlCommand Intialize(string query, params SqlParameter[] prmArray)
{
SqlConnection cn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, cn);
if (!query.Contains(" "))
cmd.CommandType = System.Data.CommandType.StoredProcedure;
if (prmArray.Length > 0)
cmd.Parameters.AddRange(prmArray);
cn.Open();
return cmd;
}
public int ExcuteNonQuery(string query, params SqlParameter[] prmArray)
{
try
{
SqlCommand cmd = Intialize(query, prmArray);
int affectedRows = cmd.ExecuteNonQuery();
cmd.Connection.Close();
return affectedRows;
}
catch (SqlException ex)
{
return ex.Number;
}
}
public object ExcuteScalar(string query, params SqlParameter[] prmArray)
{
try
{
SqlCommand cmd = Intialize(query, prmArray);
object value = cmd.ExecuteScalar();
cmd.Connection.Close();
return value;
}
catch (SqlException ex)
{
return ex.Number;
}
}
public SqlDataReader ExcuteReader(string query, params SqlParameter[] prmArray)
{
SqlCommand cmd = Intialize(query, prmArray);
SqlDataReader sqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return sqlDataReader;
}
public DataTable ExcuteDataTable(string query, params SqlParameter[] prmArray)
{
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(query, connectionString);
if (!query.Contains(" "))
sqlDataAdapter.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
if (prmArray.Length > 0)
sqlDataAdapter.SelectCommand.Parameters.AddRange(prmArray);
DataTable dt = new DataTable();
sqlDataAdapter.Fill(dt);
return dt;
}
public DataSet ExcuteDataSet(string query, params SqlParameter[] prmArray)
{
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(query, connectionString);
if (!query.Contains(" "))
sqlDataAdapter.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
if (prmArray.Length > 0)
sqlDataAdapter.SelectCommand.Parameters.AddRange(prmArray);
DataSet ds = new DataSet();
sqlDataAdapter.Fill(ds);
return ds;
}
}
}
In form patient(Table Patient) I create save method and works fine:
public void Save()
{
DBAccess db = new DBAccess();
db.ExcuteNonQuery("insert into Patients (FileNum,PatientTypeID,EngName,NationalityID,RelegionID) values (#FileNum,#PatientTypeID,#EngName,#NationalityID,#RelegionID)",
new SqlParameter("#FileNum", txtFileNum.Text),
new SqlParameter("#PatientTypeID", txtPatientTypeID.Text),
new SqlParameter("#EngName", txtEngName.Text),
new SqlParameter("#NationalityID", txtNationalityID.Text),
new SqlParameter("#RelegionID", txtRelegionID.Text)
);
}
My question is how to make classes for each table in the database?

Use existing solutions like EntityFramework. It provided all the functionality you need and it will make your life much easier than writing it all yourself (and I know, I have done it).

Creating a data access layer is a very critical part of any application. It has to be a separate library so that you can use it in any project today and in the future. Say, tomorrow you want your windows app to be converted to a web application! You can add the DAL libray and start using it.
Having said that, building your own DAL is time cosuming and its like reinventing the wheel. So you need to explore available options which might suite your requirements. Out of the box you have an ORM called EntityFramework. Its pretty straight forward to use but performace wise, its slow compared to handwritten sql. There is also another popular ORM called NHibernate. Its original counterpart Hibernate is huge in java community but it has a very steep learning curve.
But i like to use PetaPoco. It gives best of both worlds. ORM + sql. There are also other such micro ORMs like Dapper, Massive, etc. You need try each one of them and pick the one that suits your application at hand.
Even after choosing a framework that fits your bill, you need to create abstractions to make sure you can change frameworks later if required. Creating a proper DAL is a huge undertaking and has taken big chunk of my time as a developer to get things right. You can explore and find it out by your self. Good luck.

Related

SqlDataReader vs DataSet

I am attempting to get the information of user whenever user logged in to the website, it success when I used a DataSet, but if I want to use the SqlDataReader, the error says: Invalid attempt to read when reader is closed. I have search why is it like that and I have found an article says that
SqlDataReader requires connection remains open in order to get the
data from the server, while DataSet does not need requires
connection remains open.
My question is: I want to know how can I use SqlDataReader as well? So that I don't have to depends on DataSet all the times when I want to get the data from the database.
My problem is occurs when I am trying to change the structure of reading the data function using SqlDataReader, so that it can be re-usable anytime.
Here is the code:
DatabaseManager class:
public SqlDataReader GetInformationDataReader(string procName, SqlParameter[] parameters)
{
SqlDataReader reader = null;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(procName, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
if (parameters != null)
{
foreach(SqlParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
}
reader = cmd.ExecuteReader();
}
}
return reader;
}
Web Manager class:
public ModelContexts.InformationContext GetInformation(string username)
{
SqlDataReader reader = null;
ModelContexts.InformationContext context = new ModelContexts.InformationContext();
SqlParameter[] parameters =
{
new SqlParameter("#Username", SqlDbType.NVarChar, 50)
};
parameters[0].Value = username;
try
{
reader = DatabaseManager.Instance.GetInformationDataReader("GetInformation", parameters);
while(reader.Read())
{
context.FirstName = reader["FirstName"].ToString();
context.LastName = reader["LastName"].ToString();
context.Email = reader["Email"].ToString();
}
}
catch(Exception ex)
{
throw new ArgumentException(ex.Message);
}
return context;
}
Controller:
public ActionResult MainMenu(ModelContexts.InformationContext context, string firstName, string lastName, string username, string email)
{
context = WebManager.Instance.GetInformation(User.Identity.Name);
firstName = context.FirstName;
lastName = context.LastName;
username = User.Identity.Name;
email = context.Email;
return View(context);
}
Model contains string return value with getter and setter (FirstName, LastName and Email).
View contains the html label and encode for FirstName, LastName and Email from the Model.
Appreciate your answer.
Thanks.
Here is an approach you can use to keep the code pretty clean that allows you to read from the SqlDataReader while the connection is still open. It takes advantage of passing delegates. Hopefully the code is understandable. You can adjust it to fit your specific needs, but hopefully it illustrates another option at your disposal.
public void GetInformationDataReader(string procName, SqlParameter[] parameters, Action<SqlDataReader> processRow)
{
SqlDataReader reader = null;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(procName, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
if (parameters != null)
{
foreach(SqlParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
}
using (SqlDataReader dataReader = cmd.ExecuteReader())
{
while (dataReader.Read())
{
// call delegate here.
processRow(dataReader);
}
}
}
}
return reader;
}
public ModelContexts.InformationContext GetInformation(string username)
{
SqlDataReader reader = null;
ModelContexts.InformationContext context = new ModelContexts.InformationContext();
SqlParameter[] parameters =
{
new SqlParameter("#Username", SqlDbType.NVarChar, 50)
};
parameters[0].Value = username;
try
{
// Instead of returning a reader, pass in a delegate that will perform the work
// on the data reader at the right time, and while the connection is still open.
DatabaseManager.Instance.GetInformationDataReader(
"GetInformation",
parameters,
reader => {
context.FirstName = reader["FirstName"].ToString();
context.LastName = reader["LastName"].ToString();
context.Email = reader["Email"].ToString();
});
}
catch(Exception ex)
{
throw new ArgumentException(ex.Message);
}
return context;
}
Brief explanation:
You'll notice that the overall structure of the code is very similar to what you already have. The only changes are:
Instead of returning a SqlDataReader, the GetInformationDataReader() method accepts an Action<SqlDataReader> delegate.
Within the GetInformationDataReader() method, the delegate is invoked at the correct time, while the connection is still open.
The call to GetInformationDataReader() is modified to pass in a block of code as a delegate.
This sort of pattern can be useful for exactly these cases. It makes the code reusable, it keeps it pretty clean and separate, and it doesn't prevent you from benefiting from the using construct to avoid resource/connection leaks.
You have wrapped your SqlConnection object in a using clause, therefore at the end of it SqlConnect.Dispose is called, closing the connection. Whatever caller is consuming your SqlDataReader no longer has the open connection, therefore you're getting your error.
while DataSet does not need requires connection remains open.
That is not entirely correct. DataSet is just an object that is typically filled when called by SqlDataAdapter (the Fill() method of that class). The SqlDataAdapter handles the opening and closing of the SqlConnection, which is most likely why that comment states that. But it's a different class that handles that, not the DataSet itself. Think of the DataSet as just the object that holds the result set of the SqlCommand.
To answer your comment...
So, shouldn't I use using keyword for this matter? In all of the Sql keyword?
I wouldn't take that approach either. You could have a connection leak bug quite easily with that model, and running out of pooled connections could be a not-so-fun thing to troubleshoot.
Typically it's best to consume your data and then close/dispose your connection. There's a saying, "open late, close early". That's typically how you'd want to approach this. I wouldn't try to pass a SqlDataReader object between class methods for this very issue that you're dealing with. The workaround (leaving the connection open) is very error prone.
Another though process, going back to something we mentioned, don't use the SqlDataReader. You have no benefit to cyclically loop through reading each row. Depending on your result set, just fill a DataSet (or usually more appropriate, a DataTable) and return either that Data[Set | Table] or, even better, an object that is more representative of the data it pertains to.

Database method to work with any type of provider

So far my program only dealt with Sql Server for any type of data work. I would like my program to work with MySql as well. And now that I making this change, I would like to avoid code repetition as much as I can. So I started thinking about having a Factory Pattern with two concrete factories SqlServerFactory and MySqlFactory. This will work! But many of my database methods have pretty much the same structure except that in one, we are using an SqlConnection and SqlCommand and the other we are using a MySqlConnection and the rest of the method code is basically the same. Below is a example of one of my SELECT methods:
public DataTable GetSpyList()
{
DataTable dt = new DataTable();
using (OleDbConnection conn = new OleDbConnection(cs))
{
try
{
string query = "SELECT * FROM SpyList";
OleDbDataAdapter da = new OleDbDataAdapter(query, conn);
conn.Open();
da.Fill(dt);
conn.Close();
return dt;
}
catch (Exception ex)
{
return null;
}
}
}
How can I reduce code repetition by making the above method work for any type of data provider? Is this something that can be achieved by using DbProviderFactories?
Yes, the static DbProviderFactories and the DbProviderFactory class are fit for your purposes.
Of course, every abstraction like this is based on the common functionality of the base classes DbConnection, DbCommand, DbDataReader, DbDataAdapter.
For example. In the MySqlDataReader class you could find an overload of the method GetString that takes as input the name of the column to retrieve. This overload doesn't exists in the SqlDataReader and you need to use the ordinal position of the column to retrieve data. So, in case of DbProviderFactory you could use only the common version of GetString between the MySql provider and the Sql Server provider (IE using the GetString method that takes the ordinal position). Luckily, Intellisense helps a lot to avoid this error.
You could rewrite your code as
public DataTable GetSpyList()
{
DbProviderFactory fac = DbProviderFactories.GetFactory("MySQL.Data.MySqlClient");
DataTable dt = new DataTable();
using(DbConnection conn = fac.CreateConnection())
{
cn.ConnectionString = cs
DbDataAdapter da = fac.CreateDataAdapter();
da.SelectCommand = conn.CreateCommand();
da.SelectCommand.CommandText = "SELECT * FROM SpyList";
try
{
conn.Open();
da.Fill(dt);
return dt;
}
catch (Exception ex)
{
return null;
}
}
}
This example uses a fixed name for the Data Provider, but of course, you could read this name from some kind of configuration file and have your program change its underlying database changing the entry in the configuration file.

adding and quering the database in visual studio 2012 [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have added my database as a data source to my C# project in visual studio. Now, I would like to query the database. Do I need to manually set up a connection string with the database?
public void setSQL()
{
string ConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\jasper\\Desktop\\AutoReg\\AutoReg.accdb;";
OleDbConnection MyConn = new OleDbConnection(ConnStr);
MyConn.Open();
DataSet ds = new DataSet();
//query to ask
string query = "SELECT * FROM Student";
using (OleDbCommand command = new OleDbCommand(query, MyConn))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
adapter.Fill(ds);
dataGridView1.DataSource = ds;
MyConn.Close();
}
}
}
Do I need to go through all of this process every time when I need to query a database?
If you're just manually setting up a db connection for literally just one query, there isn't really an easier way to do it. I would suggest that the code be cleaned up a little, though. As it is written in your example, MyConn will remain open if there is an error during your query. That can be fixed by switching it up and putting it in a using:
public void setSQL()
{
string ConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\jasper\Desktop\AutoReg\AutoReg.accdb;";
DataSet ds = new DataSet();
//query to ask
string query = "SELECT * FROM Student";
using (OleDbConnection MyConn = new OleDbConnection(ConnStr))
{
MyConn.Open();
using (OleDbCommand command = new OleDbCommand(query, MyConn))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
adapter.Fill(ds);
}
}
}
dataGridView1.DataSource = ds;
}
If you wanted to switch this up and make it easier for you if you need to add more queries in the future, though, then I'd suggest moving to a 3-tier architecture with a Business Logic Layer (BLL) and a Data Access Layer (DAL). In this, you could have a base DAL class that defines some standard methods for things like Fill(), ExecuteScalar(), ExecuteNonQuery(), etc.
You can find countless examples of this kind of set up across the internet, but I've put together a fairly simple example:
Here's a rough sketch of a possible DAL base class. Notice how it manages the actual connections to the database based on a DB command that is passed in:
public abstract class DALBase
{
private const string connStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\jasper\Desktop\AutoReg\AutoReg.accdb;";
protected DataSet Fill(OleDbCommand command)
{
DataSet ds = new DataSet();
using (OleDbConnection myConn = new OleDbConnection(connStr))
{
command.Connection = myConn;
myConn.Open();
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
adapter.Fill(ds);
}
}
return ds;
}
protected void ExecuteNonQuery(OleDbCommand command)
{
using (OleDbConnection myConn = new OleDbConnection(connStr))
{
command.Connection = myConn;
myConn.Open();
command.ExecuteNonQuery();
}
}
// put any other methods you need here
}
And then you can make a table-specific DAL class for your Student table to handle the queries and commands. This keeps your query logic all in one place:
public class StudentDAL : DALBase
{
public DataSet GetAllStudents()
{
DataSet ds = null;
//query to ask
string query = "SELECT * FROM Student";
using (OleDbCommand command = new OleDbCommand(query))
{
ds = Fill(command);
}
return ds;
}
public void UpdateStudentName(int studentID, string name)
{
string query = "UPDATE Student SET Name = #Name WHERE StudentID = #StudentID";
using (OleDbCommand command = new OleDbCommand(query))
{
command.Parameters.AddWithValue("#Name", name);
command.Parameters.AddWithValue("#StudentID", studentID);
ExecuteNonQuery(command);
}
}
}
Then, you would make a table-specific BLL class to handle any intermediary logic that needs to happen between the DAL and the class that needs the information from your database:
public class StudentBLL
{
private _studentDAL = new StudentDAL();
public DataSet GetAllStudents()
{
return _studentDAL.GetAllStudents();
}
public void UpdateStudentName(Student student)
{
_studentDAL.UpdateStudentName(student.StudentID, student.Name);
}
}
In this particular case, the methods pretty much just make calls to the corresponding DAL. If you needed to do any other logic, though (type conversion, some kind of formula, etc.), this is where it would happen. I guess my hypothetical UpdateStudentName method, is a minor example of this. If you look at it, you'll see that it just takes in a Student object and splits it out to send to the DAL. This prevents the UI layer (or other calling class) from needing to worry about this.
Finally, you would make a call to your database through a BLL object from the class that needs the information:
public class SomeOtherClass
{
DataGridView dataGridView1;
public void PopulateDataGridView1()
{
dataGridView1.DataSource = new StudentBLL().GetAllStudents();
}
}
Now, this may not fit exactly into your needs, and I'm sure people could argue about this sort of approach, but this is meant to be more of an example of how you could go about streamlining your data access to make it far more maintainable and scalable down the road.

It don't get any data from DataReader

i work with N tiers tec in C# for ado, trying to make it easy to use and capable to change any database kind with out write all the cod all over again ,
my code here doesn't get any error but it doesn't get any values to my textbox
(i am trying to get data from table to many textboxs to update it later)
and here how code works:{
at first i make some functions to take any set any kind of parameters or set any command and then i make other function to to execute what ever i set or get from database all that Function i build it in folder name (Data Access Layer)
then i made other folder (Data Build layer)to take use all those function for what ever i want to do in any page (insert , update , delete , Select),
the last think i do it to call the function i made at at (Data Build layer) to my page or control ,
i do all that because if i Change the database Type ,i change only one class and other classes still the same
i hope i explain enough (sorry for my English not good enough)}
Code :
Class DataAccessLayer
public static void Setcommand (SqlCommand cmd,CommandType type,string commandtext)
{
cmd.CommandType=type;
cmd.CommandText=commandtext;
}
public static void AddSQLparameter(SqlCommand cmd, int size,SqlDbType type,object value,string paramName,ParameterDirection direction)
{
if (cmd == null)
{
throw (new ArgumentException("cmd"));
}
if (paramName == null)
{
throw (new ArgumentException("paramName"));
}
SqlParameter param=new SqlParameter();
param.ParameterName= paramName;
param.SqlDbType=type;
param.Size=size;
param.Value=value;
param.Direction=direction;
cmd.Parameters.Add(param);
}
public static SqlDataReader ExecuteSelectCommand(SqlCommand cmd)
{
if (cmd == null)
{
throw (new ArgumentNullException("cmd"));
}
SqlConnection con = new SqlConnection();
cmd.Connection = con;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
con.Close();
return dr ;
}
Class DatabuildLayer
SqlCommand com;
public DatabuildLayer()
{
com = new SqlCommand();
//
// TODO: Add constructor logic here
//
}
public SqlDataReader SelectCatalog(int catid)
{
DataAccessLayer.Setcommand(com, CommandType.Text, "select catname,catdescription,photo from category where catid=#catid" );
DataAccessLayer.addSQLparameter(com,16,SqlDbType.Int,catid,"#catid",ParameterDirection.Input);
return DataAccessLayer.ExecuteSelectCommand(com);;
}
and here my last code that retrieve my data to some textbox
in my Pageload :
protected void Page_Load(object sender, EventArgs e)
{
DatabuildLayer= new DatabuildLayer();
SqlDataReader dr ;
dr = obj.SelectCatalog(catselectddl.SelectedIndex);
if (dr.Read())
{
catnametxt.Text = dr["catname"].ToString();
catdestxt.Text = dr["catdescription"].ToString();
}
}
Is it possible that the query is returning nothing, and dr.Read() is returning false? Assuming the code actually executes (it is hard to tell from here) that is probably the only thing that would stop it working - either that or empty columns.
For what it is worth I think that your code needs to be tidied up a bit from a structural and conventions point of view. You should probably look through your code and consider the naming guidelines for the .NET framework. When others read your code they will want it formatted and consistent with this documentation. http://msdn.microsoft.com/en-us/library/xzf533w0(v=vs.71).aspx
Further, most people doing ASP.NET these days try to look for some way to inject external dependencies (such as databases) into their code using a framework like WebFormsMVP available at
http://webformsmvp.com/ in conjunction with an IoC container like autofac available at http://code.google.com/p/autofac/.
Using this approach you can push all external dependencies out of your application behind interfaces which would make it fairly trivial to plug in a different database engine.
Your current wrapper code is not doing anything particularly useful (just subsituting the existing methods or your own tht do the same thing), and it is not closing the connections correctly. It is... a bit of a mess.
If you aren't already massively familiar with the raw ADO.NET interfaces, then maybe consider something like "dapper" which will do all this for you, with a sane API:
short catid = 16;
using(var conn = GetOpenConnection()) {
var row = conn.Query(
"select catname,catdescription,photo from category where catid=#catid",
new { catid }).FirstOrDefault();
if(row != null) {
string name = row.catname, desc = row.catdescription;
// ...
}
}
Or if you have a class with CatName / CatDescription properties:
var obj = conn.Query<Catalogue>(
"select catname,catdescription,photo from category where catid=#catid",
new { catid }).FirstOrDefault();
from my experience, when you close a connection associated with a DataReader, nothing can be retrieved from the reader anymore.
//You closed the connection before returning the dr in the your method below:
public static SqlDataReader ExecuteSelectCommand(SqlCommand cmd)
{
if (cmd == null)
{
throw (new ArgumentNullException("cmd"));
}
SqlConnection con = new SqlConnection();
cmd.Connection = con;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
con.Close(); //here your connection was already closed
return dr ; //this dr is disconnected
}

Issues querying Access '07 database in C#

I'm doing a .NET unit as part of my studies. I've only just started, with a lecturer that as kinda failed to give me the most solid foundation with .NET, so excuse the noobishness.
I'm making a pretty simple and generic database-driven application. I'm using C# and I'm accessing a Microsoft Access 2007 database.
I've put the database-ish stuff in its own class with the methods just spitting out OleDbDataAdapters that I use for committing. I feed any methods which preform a query a DataSet object from the main program, which is where I'm keeping the data (multiple tables in the db).
I've made a very generic private method that I use to perform SQL SELECT queries and have some public methods wrapping that method to get products, orders.etc (it's a generic retail database).
The generic method uses a separate Connect method to actually make the connection, and it is as follows:
private static OleDbConnection Connect()
{
OleDbConnection conn = new OleDbConnection(
#"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Temp\db.accdb");
return conn;
}
The generic method is as follows:
private static OleDbDataAdapter GenericSelectQuery(
DataSet ds, string namedTable, String selectString)
{
OleDbCommand oleCommand = new OleDbCommand();
OleDbConnection conn = Connect();
oleCommand.CommandText = selectString;
oleCommand.Connection = conn;
oleCommand.CommandType = CommandType.Text;
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = oleCommand;
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(ds, namedTable);
return adapter;
}
The wrapper methods just pass along the DataSet that they received from the main program, the namedtable string is the name of the table in the dataset, and you pass in the query you wish to make.
It doesn't matter which query I give it (even something simple like SELECT * FROM TableName) I still get thrown an OleDbException, stating that there was en error with the FROM clause of the query. I've just resorted to building the queries with Access, but there's still no use. Obviously there's something wrong with my code, which wouldn't actually surprise me.
Here are some wrapper methods I'm using.
public static OleDbDataAdapter GetOrderLines(DataSet ds)
{
OleDbDataAdapter adapter = GenericSelectQuery(
ds, "orderlines", "SELECT OrderLine.* FROM OrderLine;");
return adapter;
}
They all look the same, it's just the SQL that changes.
Have you tried something more simple to see if you have connectivity to the table you are looking for. Something like
DataSet ds = new DataSet();
using (OleDbConnection myConnection = new OleDbConnection
(#"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Temp\db.accdb"))
{
myConnection.Open();
OleDbDataAdapter myAdapter = new OleDbDataAdapter("SELECT OrderLine.* FROM OrderLine;, myConnection);
myAdapter.TableMappings.Add("Table", "TestTable");
myAdapter.Fill(ds);
}
Then from there check to see if stuff is in ds with
ds.Tables[0].Rows.Count()
This will actually show you if you are hitting the DB and getting results. From there you can make it more elegant
Square brackets seem to have fixed the problem. Turns out I was using a keyword. Hmph.

Categories