This works if - and only if - you are using psql:
postgres@berry-pc :~$ psql template1 psql (8.4.10) Type "help" for help. template1=
\connect is the psql command. This is not regular SQL, so you cannot use it in a .sql file. As far as I know, there is no way to do this from the sql file. The rationale for this is that you should reconnect to another database as soon as you want to use this other database. This is for dividing the database. The reason MySQL implemented the use $database syntax is due to the lack of a schema, but PostgreSQL does not have such a command, since the database must be shared in the schema, not in the databases.
source share