The site is currently in read-only mode for maintenance. Posting of new items will be available again shortly.
Often times, I have found myself in a situation where I wanted to interact with a database, be it MS SQL Server, SQL Express, or Access. My enthusiasm that came with me when starting to work on a new application would be shattered right from the start, when I was to face the "connection string". And this was only the beginning; things would get worse when I had to perform even the simplest task, such as running a
Select statement. And when I had to run a Stored Procedure, I knew from the start I had to spare some time in advance.
Not anymore. After running into the same annoying things over and over again, I decided to put together an assembly that took care of all the details for me. Here are the main features:
- The connection string is history. Now, all you have to do, once you decide to give my code a try, is to specify the server name, database name, username and password. You can choose to specify the connection type (in the case of SQL Server, but if you don't, the assembly will decide which one to use based on whether or not you specified a username).
SqlDatabase db = new SqlDatabase();
db.ConnectionString.Server = @"(local)";
db.ConnectionString.AuthenticationType = AuthenticationTypes.Sql;
db.ConnectionString.Username = "myusername";
db.ConnectionString.Password = "mypassword";
You can check whether the server connection is available or whether a database, a table, or a Stored Procedure exists, by calling a single method.
You can create or drop a database directly from C#, and know whether the action was successful or not.
The feature I like the most is the ability to call Stored Procedures without having to bother too much about the parameters. Here's how to do it:
ds = db.RunStoredProcedure("getPromotion", Helpers.CreateSqlParamater("@name", "p1") );
for (int i = 0; i < ds.Tables.Rows.Count; i++)
Console.Write (ds.Tables.Rows[i]["id"] + " ");
You can create a SQL parameter or an Access parameter by calling the corresponding static function, to which you specify the parameter name, as it will be passed to the Stored Procedure, and its value. The function is overloaded to accept some basic parameter types. After that, you need to pass these parameters to the Stored Procedure function call, and you're done! Now you can process the data set.
Another useful method for SQL is called
RunScript, and with it, you can run a SQL script, just as you would from SQL Query Analyser. The transactions must be separated by the word "
GO" (on a new line), just like in Query Analyser.
I hope you all like this as much as I do and, if you have any suggestions on how I can improve the code, please let me know.