views:

239

answers:

2

What is the best way to code the following generic data access functions (ADO.NET, C# or VB, SQLServer or OLEDB)

  1. Execute SQL on a connection
  2. Open a DataReader
  3. Open a DataSet (any ideas on this one?)

Such that I can call these functions from anywhere in my program. I'm not interested in Data Access patterns or Data Access layers unless they directly apply to these functions. (i.e. a pattern to automatically close the connection or the reader/dataset)

Examples of use


ExecuteSQL("UPDATE tblTest SET x = 5 WHERE [ID] = 4")

Using rdr As OleDb.OleDbDataReader = OpenReader("SELECT * FROM tblExecute")
  While rdr.Read()

  End While
End Using

Example functions


    Public Function ExecuteSQL(ByVal strSQL As String) As Boolean
        Using cn As New OleDb.OleDbConnection(strConn)
            cn.Open()
            Using cmd As New OleDb.OleDbCommand(strSQL, cn)
                Return cmd.ExecuteNonQuery() > 0
            End Using
        End Using
        Return False
    End Function

    Public Function OpenReader(ByVal strSQL As String) As OleDb.OleDbDataReader
        Dim cn As New OleDb.OleDbConnection(strConn)
        cn.Open()
        If cn.State = ConnectionState.Open Then
            Dim cmd As New OleDb.OleDbCommand(strSQL, cn)
            Return cmd.ExecuteReader(CommandBehavior.CloseConnection)
        Else
            Throw New Exception("Unable to connect to database.")
        End If
    End Function

+1  A: 

Here's my Fill method which, given a generic list and a lambda, populates the list with objects read from an IDataReader:

public static void Fill<T>(this IDbCommand cmd,
    IList<T> list, Func<IDataReader, T> rowConverter)
{
    using (var rdr = cmd.ExecuteReader())
    {
        while (rdr.Read())
        {
            list.Add(rowConverter(rdr));
        }
    }
}

You use it like this:

// var cmd = new SqlCommand(...);
// var things = new List<Thing>();
cmd.Fill(things, r => new Thing { ID = r.GetInt32(0), Name = r.GetString(1) });

Really handy to be able to wrap up that ExecuteReader and Read loop in one line like that.

Matt Hamilton
+1  A: 

If that's all you want then the code you have posted is essentially sufficient. As for what is best ... Well, I suggest using one of those "Data Access patterns." But this does work and there's not much more to be said. You add other functions for ExecuteScalar and so forth if you'd like.

You're basically just using strings, if you are concatenating or building your SQL then that is very bad. If you are doing that you should really be use Parameterized queries and extending your functions to use parameter collections and the like.

BobbyShaftoe