BV infection

How do you get bacterial vaginosis? Is it just from sex? Is it the shaving cream I’m using down there? How do I prevent it?