检查MS Access数据库表(如果不存在)创建它

LEM*_*ANE 9 c# ms-access

如何以编程方式检查MS Access数据库表,如果不存在则创建它?

小智 13

您可以迭代表名以检查特定表.请参阅以下代码以获取表名称.

        string connectionstring = "Your connection string";
        string[] restrictionValues = new string[4]{null,null,null,"TABLE"};
        OleDbConnection oleDbCon = new OleDbConnection(connectionString);
        List<string> tableNames = new List<string>();

        try
        {
            oleDbCon.Open();
            DataTable schemaInformation = oleDbCon.GetSchema("Tables", restrictionValues);

            foreach (DataRow row in schemaInformation.Rows)
            {
               tableNames.Add(row.ItemArray[2].ToString());
            }
        }
        finally
        {
            oleDbCon.Close();
        }           
Run Code Online (Sandbox Code Playgroud)


csn*_*910 9

要检查表是否存在,您可以像这样扩展DbConnection:

public static class DbConnectionExtensions
{
    public static bool TableExists(this DbConnection conn, string table)
    {
        conn.open();
        var exists = conn.GetSchema("Tables", new string[4] { null, null, table, "TABLE" }).Rows.Count > 0;
        conn.close();
        return exists;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以在OleDbConnection,SQLiteConnection或SqlConnection等任何派生类中调用TableExists.


She*_*Pro 8

如果表存在,只需执行以下代码,它将返回错误,否则它将创建一个新的:

try
{
        OleDbConnection myConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + frmMain.strFilePath + "\\ConfigStructure.mdb");
        myConnection.Open();
        OleDbCommand myCommand = new OleDbCommand();
        myCommand.Connection = myConnection;
        myCommand.CommandText = "CREATE TABLE <yourtable name>(<columns>)";
        myCommand.ExecuteNonQuery();
        myCommand.Connection.Close();
}
catch(OleDbException e)
{  
    if(e.ErrorCode == 3010 || e.ErrorCode == 3012)
    // if error then table exist do processing as required
}
Run Code Online (Sandbox Code Playgroud)

如果表已经存在,则返回这些错误代码 - 请在此处查看所有错误代码.