views:

63

answers:

2

Hi guys.

I'm making a DAL class which I can use to connect to DB and retrieve data. I'm using SQL Server 2005 Express (and Visual Web Developer 2008 Express Edition).

I found several examples on the web for connecting an retrieving data. But none where made inn to a class object.

This is kind of a pseudocode I've put together. Can anyone help me with some code which I can use to get data from MS DB?

namespace development.DAL {

    public class myDAL
    {
        SqlConnection conn;
        string conStr = "myConnectionString";

        public myDAL()
        {
            string connStr = Config.Get(this.conStr);
            this.conn = new SqlConnection(connStr);
        }

        // Function for retrieving data from DB
        public DataSet GetAllRows(string table)
        {

            string sql = string.Format(@"
       SELECT *
       FROM '{0}';
       ", table);

            DataSet dbDataSet = Command.CreateDataSet(cmd);  //Pseudocode!
            return dbDataSet;
        }
    }
}
A: 

Search online for the repository pattern, I think that's what you are looking for. It'll help you abstract the data storage from the actual mechanics of accessing the database. Additionally, you'll find it easier to test and debug (or at least I do).

Lazarus
.. and perhaps OP could also look at "SQL injection" too
gbn
Not familiar with 'OP'
Lazarus
"original poster"
gbn
Ah! Good advice ;)I'm still astonished how often you still see published examples of that kind, beginners are then lead... by the hand... into bad habits. Sometimes I think it would better to give an example of good practice that takes a bit more explanation rather than the quick and dirty one, after all long after the quick has departed the dirty remains.
Lazarus
I don't know about you guys, but I don't handle 'SQL injection' prevention in my DAL.
Steven
It's the safest place to do it.
Lazarus
+1  A: 

Steven, There are also code generators out there that will create a complete DAL layer for you. Often the procedure is as simple as pointing the code generator at a db, selecting your tables and clicking go...

Check out: http://www.mygenerationsoftware.com (free, open source and my current fave) http://www.codesmithtools.com (solid, professional, no longer free but with free trial)

And there are literally dozens of others.

Paul Sasik
hmm... will have a look at this. But it would be really cool if someone could cut'n'paste an example in here though :)
Steven
Thanks for the tip psasik. Will have a closer look at this tomorrow. This one looks good to: http://subsonictools.codeplex.com
Steven