0

我正在制作一个桌面 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;
    }
}

}

4

1 回答 1

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;
}
于 2013-11-14T13:48:07.610 回答