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