calibre provides a full programmatic interface to the database via the calibre-debug command
Code:
calibre-debug -c "from calibrelibrary.database2 import LibraryDatabase2; db = LibraryDatabase2('/path/to/library/folder'); db.execute('some sql statement');"
You can also use
calibre-debug -e path_to_script.py
to execute long scripts