问题
What is the best way to code the following generic data access functions (ADO.NET, C# or VB, SQLServer or OLEDB)
- Execute SQL on a connection
- Open a DataReader
- 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