Execute ad hoc database commands such as CREATE TABLE, INSERT INTO, DROP TABLE, and so forth in C#

ADO.NET doesn't provide much in the way of objects to manipulate a database's structure. Fortunately this is fairly easy by executing SQL statements.

This example uses OLE DB to connect to an access database. (Unfortunately this technique cannot create a database but you can use any old database and then modify it using this technique.)

When the program starts, the following code executes to prepare the connection object. It doesn't actually open the connection yet, though.

// The connection object.
OleDbConnection conn;

// Prepare the connection to open later.
private void Form1_Load(object sender, EventArgs e)
{
// Compose the database file name.
// This assumes it's in the executable's directory.
string file_name = Application.StartupPath + "\\Books.mdb";

// Connect.
conn = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + file_name + ";" +
"Mode=Share Deny None");

// Select the first sample command.
cboSamples.SelectedIndex = 0;
}

Use the combo box to select a sample command or type one into the TextBox and then click Execute. The following code shows how the program executes the command in the TextBox.

// Execute the command.
private void btnExecute_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = txtCommand.Text;

try
{
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Done");
}
catch (Exception ex)
{
MessageBox.Show("Error executing command.\n" + ex.Message);
}
finally
{
conn.Close();
}
}

The code creates an OleDbCommand object. It sets its Connection property so it knows over which connection to execute, and sets its Command property so it knows what to do.

The program then opens the connection, executes the command, and closes the connection. That's all there is to it.

Note that in general you should not let users execute ad hoc commands because they could destroy data, damage the database structure, and generally wreak havoc. This example is really just to show you how you can let your program use command objects.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.