开发者

Validate database file schema before open

开发者 https://www.devze.com 2023-03-29 23:43 出处:网络
I have an application that saves and opens data (which is saved as SQL CE database file). Every time the project gets saved, a new .sdf file is generated with table structure defined by my code and I

I have an application that saves and opens data (which is saved as SQL CE database file). Every time the project gets saved, a new .sdf file is generated with table structure defined by my code and I do not need to run any validation against it.

My concern is when user import (open) the .sdf file in a OpenFileDialog, there will be chance user may select a database file generated from a different application (i.e. having a different table schema). I would need to validate the importing database table schema or the application may crash if the wrong database file is opened and processed.

I do not need to compare schema between files. All I need is to check if the database file contain a certain table structure or table names (which I think should be sufficient for my purpose). What is the easiest way to do this?

[EDIT]

I used the following method to validate the database file, which works. I use a string array to checked against a SqlCeDataReader (which stores the Table name). It works but I wonder if there's an even easier way - is there a build in method in .NET to use?

using (SqlCeConnection conn = new SqlCeConnection(validateConnStr))
{
    using (SqlCeCommand cmd = new SqlCeCommand(@"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES", conn))
    {
        try
        {
            conn.Open();
            SqlCeDataReader rdr = cmd.ExecuteReader();
            string[] tableArr = { "FirstTable", "SecondTable" };
            int ta = 0;
            while (rdr.Read())
            {
                if (rdr.GetString(0) != tableArr[ta])
                {
                    isValidDbFile = false;
                }
                else
                {
                    isValidDbFile = true;
                }
                ta++;
            }
        }
        catch (Exception ex)
        {
            //MessageBox.Show(ex.开发者_如何学JAVAToString());
        }
        finally
        {
            conn.Close();
        }
    }
}


Open the database (make sure to have error handling for this, as the user can point to any file).

run: SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'MyTable'

If this returns data, your table is there.

0

精彩评论

暂无评论...
验证码 换一张
取 消