如何知道 OleDb 连接的访问数据库中是否存在表



我使用以下代码通过OleDb连接连接到 Access 数据库C# .Net

如何知道我已硬编码到程序中的表是否确实存在于文件中,以便我可以向用户显示相应的消息?

try
{
    var dbSource = "Data Source = " + source;
    const string dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;";
    using (var con = new OleDbConnection())
    {
        con.ConnectionString = dbProvider + dbSource;
        con.Open();
        using (var cmd = new OleDbCommand())
        {
            cmd.Connection = con;
            cmd.CommandText = "SELECT * FROM [Concrete Design Table 1]";
            // How do I know the table name is valid? It results in errors when it is not?
            // How to prevent it?
            using (var dataReader = cmd.ExecuteReader())
            {
                while (dataReader != null && dataReader.Read())
                {
                    // read the table here
                }
            }
        }
    }
}
catch (Exception e)
{
    MessageBox.Show(e.ToString());
}

您可以使用以下命令获取表列表

var schema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

并浏览它们:

foreach (var row in schema.Rows.OfType<DataRow>())
{
    string tableName = row.ItemArray[2].ToString();
}

或检查是否存在:

if (schema.Rows
          .OfType<DataRow>()
          .Any(r => r.ItemArray[2].ToString().ToLower() == tablename.ToLower()))
{
    // table exists
}

丑陋,我知道。:(

这是我

使用的一个工作解决方案(VB.NET,但我想你可以弄清楚 C# 变体):

Dim myTable As Object, TableSchema As Object
Dim con As OleDb.OleDbConnection
con = New System.Data.OleDb.OleDbConnection
con.ConnectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=" & myFileName & ";"
If Not con.State = ConnectionState.Open Then con.Open()
TableSchema = con.GetSchema("TABLES")
myTable = TableSchema.select("TABLE_NAME='MYTABLENAME'")
If myTable.length = 0 Then
    Dim cmd As New OleDb.OleDbCommand
    cmd.Connection = con
    cmd.CommandText = "CREATE TABLE MYTABLENAME;"
    nAffected = cmd.ExecuteNonQuery
End If

SQL错误将引发OleDbException,您可以检查SQLState指定的错误。如果该表不存在,则根据Microsoft的文档,代码应为 3376。所以你的代码应该看起来像

catch (OleDbException e)
{ 
    switch (dbException.Errors[0].SQLState)
    {
        case "3376":
            MessageBox.Show(dbException.Errors[0].Message); // or any message
            break;
        default:
            MessageBox.Show(e.Message);
    }
}

相关内容

  • 没有找到相关文章

最新更新