I’m just looking to write a generic function in C# .NET 4.0 where I can send it a database string, a query string, and get my results back.
Not being that well versed in C# and it’s various different objects, I’m not really sure what the best options might be for returning this information.
I know there is DataTable, DataSet, and that’s really about it. What I’m looking for is an object that is fairly efficient and something where I can easily access it’s data members. I’m sure it wouldn’t be a problem writing my own, but I know there has to be some other object in .NET 4.0 that I can access.
The problem with such a design is that it’s very difficult to use best practices for security and preventing SQL Injection. Passing in a pure SQL statement to a function pretty much eliminates the ability to defend against SQL Injection unless you do it carefully.
As a general rule, if you’re taking in any user input, you want to be sure that you’re either using parameterized stored procedures, or parameterized queries. The recommended pattern would be to pass in a statement and an array of type object that contains the correct number of parameter values, and build the parameter collection in your function.
We use the Microsoft data Application Blocks from their patterns and Practices library, which contain functionality that really makes this a lot easier.
In using this, the ConnectionString is stored in the app.config or web.config, and you pass in the NAME of the connection string, The Data Application Blocks code takes care of looking it up, creating the command, connection, and performing the query.
Our code looks like this when using this pattern:
This is the code for getting a DataSet. There are plenty of other functions available, and this code might not work against the newest version of the Data Access Library. We’re using a slightly older version, but this should give you an idea of how easy it is to use.