postgresql - can't create database - OperationalError: source database “template1” is being accessed by other users

左心房为你撑大大i 提交于 2019-12-02 21:43:36

Database template1 exists only to provide barebone structure to create another empty database. You should never logon to template1, otherwise you will have problems.

Probably easiest solution for you is to restart PostgreSQL server process, and logon again. Database that should always exist and is safe to logon is postgres.

If restarting is not an option, you can use another emergency template database: template0.

By default, this statement:

CREATE DATABASE dbname;

is equivalent to:

CREATE DATABASE dbname TEMPLATE template1;

If template1 is not available or corrupted, you can use template0 as last resort:

CREATE DATABASE dbname TEMPLATE template0;

You can read more about template databases here.

This helped me solve my problem:

SELECT *, pg_terminate_backend(procpid) 
FROM pg_stat_activity 
WHERE usename='username';

--Use pid if PostgreSQL version 9.2 or above.

I terminated all active connections to template1 and could create database normally

You can also try to terminate the current process thread by the Terminal

Search the Process :

sudo ps aux | grep template1

Kill the Process :

sudo kill -9 < your process id >

To solve this, I have to disconnect the database connection from the pgAdmin III.

I have a script that connects to a database and performs various operations on it, some requiring that no one else is logged in. I modified @Andrius's answer not to terminate my script's connection, but rather terminate everyone else's:

SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE pid <> pg_backend_pid();

From the docs: pg_backend_pid() is the Process ID of the server process attached to the current session.

This problem occur when you had logged(psql template1 or psql template0) in template1 and template0 database and exit using below command.

Ctrl + z

Better way exist from db use below postgres command then problem will not create:

\q + enter

There are 2 solutions, If have problem.

Solution - 1

Restart posgres service like.

sudo service postgresql restart

Solution - 2

sudo ps aux | grep template1

Make sure don't delete this processes

postgres 8363 0.0 0.0 111760 7832 pts/11 T 09:49 0:00 /usr/lib/postgresql/9.5/bin/psql template1 ankit 18119 0.0 0.0 14224 976 pts/14 S+ 12:33 0:00 grep --color=auto template1

rest of process should be kill using below command.

sudo kill -9

Now try to create db again.

Hope this help you.

Ankit H Gandhi.

On Windows I had to reinstall PostgreSQL, restart did not help.

You can try to restart the postgresql service that is running in the background.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!