如何在选定的数据库连接上执行验证?

时间:2013-11-14 12:18:35

标签: c# asp.net database visual-studio entity-framework

我正在创建一个桌面Windows应用程序,基本上选择一个数据库,连接字符串现在我想对所做的选择执行一些检查,我将如何进行此操作?。

我需要检查数据库是否包含特定的表名。

到目前为止,这是我的代码。

    private void Form1_Load(object sender, EventArgs e)
    {
        List<string> databaseName = GetDatabases();
        if (databaseName.Any())
        {
            cboxDatabases.DataSource = databaseName;               
        }
    }

    private List<string> GetDatabases()
    {
        List<String> databases = new List<String>();

        SqlConnectionStringBuilder connection = new SqlConnectionStringBuilder();
        connection.DataSource = "localhost";
        // enter credentials if you want
        //connection.UserID = //get username;
        // connection.Password = //get password;
        connection.IntegratedSecurity = true;

        String strConn = connection.ToString();
        //create connection
        SqlConnection sqlConn = new SqlConnection(strConn);

        //open connection
        sqlConn.Open();

        //get databases
        DataTable tblDatabases = sqlConn.GetSchema("Databases");

        //close connection
        sqlConn.Close();

        //add to list
        foreach (DataRow row in tblDatabases.Rows)
        {
            String strDatabaseName = row["database_name"].ToString();
            databases.Add(strDatabaseName);
        }
        return databases;
    }
}

}

1 个答案:

答案 0 :(得分:0)

您可以这样做:

public bool TableExists(SqlConnection sqlConn, string tableName) 
{
    string query = string.Format("SELECT count(*) as 'Exists' FROM dbo.sysobjects WHERE id = OBJECT_ID('[dbo].[{0}]')", tableName);

    SqlCommand cmd = new SqlCommand(query, sqlConn);

    int tableResult = (Int32)cmd.ExecuteScalar();

    return tableResult == 1;
}