QGIS provide a plugin to import|export data from a PostgresSQL database.
In QGIS 3.30 , calling this plugin result in this code :
from qgis.core import QgsDataSourceUri
from db_manager.dlg_import_vector import DlgImportVector
from db_manager.db_plugins.postgis.plugin import PostGisDBPlugin, PGDatabase
from configparser import ConfigParser
services = ConfigParser()
services.read(os.environ['PGSERVICEFILE'] if 'PGSERVICEFILE' in os.environ else os.path.join(os.path.expanduser('~'), '.pg_service.conf'))
uri = QgsDataSourceUri()
uri.setConnection(services, dbname, '', '')
dbplugin = PostGisDBPlugin(dbname)
db = PGDatabase(dbplugin, uri)
dlg = DlgImportVector(None, db, uri, None)
This give access to the plugin directly set on the given database, but you need a good pg_service.conf file in your user space to make it work properly
https://docs.postgresql.fr/10/libpq-pgservice.html
Another example that directly load a layer from the db to the QGIS project.
With the good imports and layer_name being the name of the layer in QGIS, table_name the name of the table in the given schema of the db. We also do a small job to look if a 'work' group exist , create it if not and add the layer to it.
root = QgsProject.instance().layerTreeRoot()
if root.findGroup('work') :
work_group = root.findGroup('work')
else :
work_group = root.addGroup('work')
uri = QgsDataSourceUri()
uri.setConnection(services, dbname, '', '')
uri.setDataSource('work', table_name, str(column_geom))
layer = QgsVectorLayer(uri.uri(), layer_name, "postgres")
QgsProject.instance().addMapLayer(layer, False)
work_group.addLayer(layer)
QgsProject.instance().write(QgsProject.instance().fileName())
This has changed a bit for some QGIS version, but with a bit of documentation and theses examples it should be possible. If you produce correct code, you can answer and close this.