Generic Data Access functions

倖福魔咒の 提交于 2020-01-03 05:54:07

问题


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:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/385178/generic-data-access-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!