Python PostgreSQL - Crea database
Puoi creare un database in PostgreSQL utilizzando l'istruzione CREATE DATABASE. È possibile eseguire questa istruzione nel prompt della shell di PostgreSQL specificando il nome del database da creare dopo il comando.
Sintassi
Di seguito è riportata la sintassi dell'istruzione CREATE DATABASE.
CREATE DATABASE dbname; 
    Esempio
La seguente istruzione crea un database denominato testdb in PostgreSQL.
postgres=# CREATE DATABASE testdb;
CREATE DATABASE 
    Puoi elencare il database in PostgreSQL usando il comando \ l. Se verifichi l'elenco dei database, puoi trovare il database appena creato come segue:
postgres=# \l
                                                List of databases
   Name    | Owner    | Encoding |        Collate             |     Ctype   |
-----------+----------+----------+----------------------------+-------------+
mydb       | postgres | UTF8     | English_United States.1252 | ........... |
postgres   | postgres | UTF8     | English_United States.1252 | ........... |
template0  | postgres | UTF8     | English_United States.1252 | ........... |
template1  | postgres | UTF8     | English_United States.1252 | ........... |
testdb     | postgres | UTF8     | English_United States.1252 | ........... |
(5 rows) 
    Puoi anche creare un database in PostgreSQL dal prompt dei comandi usando il comando createdb , un wrapper attorno all'istruzione SQL CREATE DATABASE.
C:\Program Files\PostgreSQL\11\bin> createdb -h localhost -p 5432 -U postgres sampledb
Password: 
    Creazione di un database utilizzando Python
La classe del cursore di psycopg2 fornisce vari metodi per eseguire vari comandi PostgreSQL, recuperare record e copiare dati. È possibile creare un oggetto cursore utilizzando il metodo cursor () della classe Connection.
Il metodo execute () di questa classe accetta una query PostgreSQL come parametro e la esegue.
Pertanto, per creare un database in PostgreSQL, eseguire la query CREATE DATABASE utilizzando questo metodo.
Esempio
L'esempio seguente di Python crea un database denominato mydb nel database PostgreSQL.
import psycopg2
#establishing the connection
conn = psycopg2.connect(
   database="postgres", user='postgres', password='password', 
   host='127.0.0.1', port= '5432'
)
conn.autocommit = True
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Preparing query to create a database
sql = '''CREATE database mydb''';
#Creating a database
cursor.execute(sql)
print("Database created successfully........")
#Closing the connection
conn.close() 
    Produzione
Database created successfully........                    