Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"use database_name" command in PostgreSQL

Tags:

postgresql

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?

like image 314
sam Avatar asked Apr 26 '12 14:04

sam


People also ask

How do I run a DB script in PostgreSQL?

Another easiest and most used way to run any SQL file in PostgreSQL is via its SQL shell. Open the SQL shell from the menu bar of Windows 10. Add your server name, database name where you want to import the file, the port number you are currently active on, PostgreSQL username, and password to start using SQL shell.


2 Answers

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.

like image 113
kgrittn Avatar answered Oct 06 '22 10:10

kgrittn


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.

like image 33
Eugene Avatar answered Oct 06 '22 09:10

Eugene