While building a wordpress site and needed to work with a separate existing database.
Added a function in wp-includes/functions.php like this:
function my_query($sql){
$db = @mysql_connect("my_DB_host", "DB_usr", "DB_pass");
mysql_select_db("my_other_database");
$result = mysql_query($sql) or die('Did not get required database result');
return $result;
mysql_close($db);
}
Then wherever I need to connect to this database I can use the function like this:
$sql = sprintf("SELECT blah FROM table");
$result = my_query($sql);