[GIS] Using raster2pgsql in Python console of QGIS

postgisqgisraster2pgsql

I have to upload GeoTiFF files into a PostGIS/PostgreSQL database and I am new to raster2pgsql.

How do I run a raster2pgsql command in the Python console?

enter image description here

import psycopg2
import subprocess

db_name = 'enter_qgiscloud_db'
db_host = 'db.qgiscloud.com'
db_user = 'enter_qgiscloud_user'
db_password = 'enter_qgiscloud_pw'

conn = psycopg2.connect( "dbname={0} host={1} user={2} password={3}".format( db_name, db_host, db_user, db_password ) )
cursor = conn.cursor()

cmds = 'raster2pgsql -s 3857 -p -Y -I -C -M C:\qgis_cloud_data\ -F -t auto .tif | psql'
subprocess.call(cmds, shell=True)

cursor.execute(cmds)
conn.commit()

Best Answer

Here's a script that iterates on all the tiff rasters in a folder and creates a table with auto tile size for each (based on this link):

import psycopg2
import subprocess 
import sys, os

input_path = " C:\\qgis_cloud_data\\"
#Change to the location of pgsql bin folder
os.environ['PATH'] = r';C:\pgsql\9.6\bin'
os.environ['PGHOST'] = 'localhost'
os.environ['PGPORT'] = '9008'
os.environ['PGUSER'] = 'postgres'
os.environ['PGPASSWORD'] = 'dbpass'
os.environ['PGDATABASE'] = 'dbname'

for raster in os.listdir(input_path):
    if raster.endswith(".tif"):
       name = raster.split(".tif")[0]
       # Print the foound tiff name
       print(name)     
       raster = os.path.join(input_path, raster)                    
       # Print the full path of the tiff raster
       print(raster)
       rastername = str(name)
       rasterlayer = rastername.lower()
       conn = psycopg2.connect(database="dbname", user="postgres", host="localhost", password="dbpass", port=9008)
       cursor = conn.cursor()
       cmds = 'raster2pgsql -s 3857 -t auto "' + raster + '" |psql'
       subprocess.call(cmds, shell=True)
Related Question