C# DataExecutor class available

One of the questions I see most frequently on Freenode's ##csharp irc channel is how to use a MySql Database in .NET. I've therefore provided the class that I use for basic database operations. You can find it at http://pro.grammatic.org/post-c-mysql-dataexecutor-class-31.aspx.

The class supports both strongly and weakly typed datasets and usage is as follows:

  1. Get the MySql Connector.NET
  2. Reference it in your project
  3. Use the following for strongly typed datasets:
  4. MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand("SELECT * FROM table WHERE blah=@blah");
    cmd.Parameters.Add("@blah", "test");
    
    Tools.DataExecutor de = null;
    
    try{
    
    	de = new Tools.DataExecutor(cmd, false);
    
    	DataSchemas.app.tableDataTable test = new DataSchemas.app.tableDataTable();
    	de.DataSetSchema(test);
    
    	DataSchemas.app.tableRow row = null;
    
    	if (test.Rows.Count > 0)
    	{
    		row = (DataSchemas.app.tableRow)test.Rows[0];
    	}
    
    } finally {
    	de.Close();
    }
    

    and this for weakly typed datasets:

    MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand("SELECT * FROM table WHERE blah=@blah");
    cmd.Parameters.Add("@blah", "test");
    
    Tools.DataExecutor de = new Tools.DataExecutor(cmd, false);
    
    DataSet ds = new DataSet();
    
    de.Adapter.Fill(ds);
    

    Easy eh? :)

    The parameterization of the queries will protect you against SQL Injection exploits so I'd recommend you do that at all times. Your connection string should go in your Web.Config file and then be specified inside the DataExecutor class. It's worth pointing out that if you don't set oldsyntax=true; then you must ensure that you use ? for your parameter names as opposed to @.

comment from Home
Typed datasets wity MySQL ??? ups.... DataSet ds = new DataSet(); THIS IS NOT TYPED DATASET TYPED DATASETS SUPPORT TABLESADAPTER, AND THESE ARE STORED IN XSD FILE. DataSet ds = new DataSet(); ????? THIS IS NOT TYPED DATASET Thanks.

comment from martin
Feel free to actually read the post, which gives an example of a typed dataset in the first section and then to turn your caps lock key off.

add a comment
name:
website:
email:
comment: