When we are regularly using databases, sometimes those will get corrupted. This happened to one of my applications, it was a Windows Mobile application with SQL Server CE database. Since it is running in a mobile it is bit difficult for us to fix the database using the desktop machine. I used the following .Net Compact framework code to fix the corrupted database while the database is in the mobile.
- private void btnRepair_Click(object sender, EventArgs e)
- {
- Cursor.Current = Cursors.WaitCursor;
- Cursor.Show();
- // txtDBPath will contain the path to the database.
- engine = new SqlCeEngine(@"Data Source=" + txtDBPath.Text + ";Password=DBPassword");
- try
- {
- if (!engine.Verify())
- {
- Cursor.Current = Cursors.Default;
- Cursor.Hide();
- DialogResult result = MessageBox.Show("Database is corrupted. Do you want to repair?", "My App", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
- if (result == DialogResult.Yes)
- {
- Cursor.Current = Cursors.WaitCursor;
- Cursor.Show();
- // You can also use RepairOption.DeleteCorruptedRows.
- engine.Repair(null, RepairOption.RecoverCorruptedRows);
- Cursor.Current = Cursors.Default;
- Cursor.Hide();
- MessageBox.Show("Database repaired successfully.", "My App");
- }
- }
- else
- {
- Cursor.Current = Cursors.Default;
- Cursor.Hide();
- MessageBox.Show("Database is not corrupted.", "My App");
- }
- }
- catch (Exception ex)
- {
- Cursor.Current = Cursors.Default;
- Cursor.Hide();
- MessageBox.Show(ex.Message, "Error!");
- }
- }