Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I am beginner to PostgreSQL.

I want to connect to another database from the query editor of Postgres - like the USE command of MySQL or MS SQL Server.

I found \c databasename by searching the Internet, but its runs only on psql. When I try it from the PostgreSQL query editor I get a syntax error.

I have to change the database by pgscripting. Does anyone know how to do it?

share|improve this question
up vote 121 down vote accepted

When you get a connection to PostgreSQL it is always to a particular database. To access a different database, you must get a new connection.

Using \c in psql closes the old connection and acquires a new one, using the specified database and/or credentials. You get a whole new back-end process and everything.

share|improve this answer
    
Thanks kgrittn for your valuable guidance.Can you tell me how I can make new connection to database and close previous by using pgscript query? – Sameer Apr 27 '12 at 6:41
    
I'm not familiar with pgscript. If that's a language in which you write functions, the answer is that it can't be done. Maybe you should consider putting tables in different schemas instead of different databases? – kgrittn Apr 27 '12 at 12:40
1  
Thanks.can we write simple query to change database???How? – Sameer Apr 27 '12 at 13:39
1  
A query can't change the database in PostgreSQL. – kgrittn Apr 28 '12 at 1:04
6  
If I'm not mistaken, databases in MySQL are more akin to schemas in PostgreSQL -- you can switch between those, but DBs in PostgreSQL are a whole different ballgame. – mpen May 10 '12 at 3:40

You must specify the database to use on connect; if you want to use psql for your script, you can use "\c name_database"

user_name=# CREATE DATABASE testdatabase; 
user_name=# \c testdatabase 

At this point you might see the following output

You are now connected to database "testdatabase" as user "user_name".
testdatabase=#

Notice how the prompt changes. Cheers, have just been hustling looking for this too, too little information on postgreSQL compared to MySQL and the rest in my view.

share|improve this answer
    
best explanation, thank you – Oleg Abrazhaev Feb 16 at 8:28

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.