pg - PyGreSQL classic interface.
| Use Case | Command | Description |
|---|---|---|
| Connect to database | DB(dbname, host, port, opt) | Create a new connection to a PostgreSQL database. |
| Execute a query | db.query(command) | Execute a SQL command string. |
| Insert a row | db.insert(table, row) | Insert a row into a database table. |
| Update a row | db.update(table, row) | Update an existing row in a database table. |
| Delete a row | db.delete(table, row) | Delete an existing row in a database table. |
| Begin transaction | db.begin() | Begin a transaction. |
| Commit transaction | db.commit() | Commit the current transaction. |
| Rollback transaction | db.rollback() | Roll back the current transaction. |
| Get a single row | db.get(table, row) | Get a row from a database table or view. |
| Get table as list | db.get_as_list(table) | Get a table as a list of named tuples. |
| Get table as dict | db.get_as_dict(table) | Get a table as a dictionary. |
| Escape a string | escape_string(string) | Escape a string for use within SQL. |
This pg module implements some basic database management stuff. It includes the _pg module and builds on it, providing the higher level wrapper class named DB with additional functionality. This is known as the "classic" ("old style") PyGreSQL interface. For a DB-API 2 compliant interface use the newer pgdb module.
Adapter(db)
Class providing methods for adapting parameters to the database.
__init__(self, db) — Initialize self. See help(type(self)) for accurate signature.adapt(self, value, typ=None) — Adapt a value with known database type.adapt_inline(self, value, nested=False) — Adapt a value that is put into the SQL and needs to be quoted.format_query(self, command, values=None, types=None, inline=False) — Format a database query using the given values and types.parameter_list(self) — Return a parameter list for parameters with known database types.guess_simple_base_type(value) from builtins.type — Try to guess the base type of a given array.guess_simple_type(value) from builtins.type — Try to guess which database type the given value has.get_attnames(typ) — Get the attribute names of a composite database type.get_simple_name(typ) — Get the simple name of a database type.simple_type(name) — Create a simple database type with given attribute names.__dict__ — dictionary for instance variables (if defined)__weakref__ — list of weak references to the object (if defined)Wrapper class for marking Bytea values.
Method resolution order: Bytea, builtins.bytes, builtins.object
__dict__ — dictionary for instance variables (if defined)__add__(self, value, /) — Return self+value.__contains__(self, key, /) — Return key in self.__eq__(self, value, /) — Return self==value.__ge__(self, value, /) — Return self>=value.__getattribute__(self, name, /) — Return getattr(self, name).__getitem__(self, key, /) — Return self[key].__getnewargs__(...)__gt__(self, value, /) — Return self>value.__hash__(self, /) — Return hash(self).__iter__(self, /) — Implement iter(self).__le__(self, value, /) — Return self<=value.__len__(self, /) — Return len(self).__lt__(self, value, /) — Return self<value.__mod__(self, value, /) — Return self%value.__mul__(self, value, /) — Return self*value.__ne__(self, value, /) — Return self!=value.__repr__(self, /) — Return repr(self).__rmod__(self, value, /) — Return value%self.__rmul__(self, value, /) — Return value*self.__str__(self, /) — Return str(self).capitalize(...) — B.capitalize() → copy of B. Return a copy of B with only its first character capitalized (ASCII) and the rest lower-cased.center(self, width, fillchar=b' ', /) — Return a centered string of length width. Padding is done using the specified fill character.count(...) — B.count(sub[, start[, end]]) → int. Return the number of non-overlapping occurrences of subsection sub in bytes B[start:end].decode(self, /, encoding='utf-8', errors='strict') — Decode the bytes using the codec registered for encoding.endswith(...) — B.endswith(suffix[, start[, end]]) → bool. Return True if B ends with the specified suffix, False otherwise.expandtabs(self, /, tabsize=8) — Return a copy where all tab characters are expanded using spaces.find(...) — B.find(sub[, start[, end]]) → int. Return the lowest index in B where subsection sub is found. Return -1 on failure.hex(...) — Create a string of hexadecimal numbers from a bytes object.index(...) — B.index(sub[, start[, end]]) → int. Return the lowest index in B where subsection sub is found. Raises ValueError when not found.isalnum(...) — B.isalnum() → bool. Return True if all characters in B are alphanumeric.isalpha(...) — B.isalpha() → bool. Return True if all characters in B are alphabetic.isascii(...) — B.isascii() → bool. Return True if B is empty or all characters are ASCII.isdigit(...) — B.isdigit() → bool. Return True if all characters in B are digits.islower(...) — B.islower() → bool. Return True if all cased characters in B are lowercase.isspace(...) — B.isspace() → bool. Return True if all characters in B are whitespace.istitle(...) — B.istitle() → bool. Return True if B is a titlecased string.isupper(...) — B.isupper() → bool. Return True if all cased characters in B are uppercase.join(self, iterable_of_bytes, /) — Concatenate any number of bytes objects.ljust(self, width, fillchar=b' ', /) — Return a left-justified string of length width.lower(...) — B.lower() → copy of B. Return a copy of B with all ASCII characters converted to lowercase.lstrip(self, bytes=None, /) — Strip leading bytes contained in the argument.partition(self, sep, /) — Partition the bytes into three parts using the given separator.removeprefix(self, prefix, /) — Return a bytes object with the given prefix string removed if present.removesuffix(self, suffix, /) — Return a bytes object with the given suffix string removed if present.replace(self, old, new, count=-1, /) — Return a copy with all occurrences of substring old replaced by new.rfind(...) — B.rfind(sub[, start[, end]]) → int. Return the highest index in B where subsection sub is found.rindex(...) — B.rindex(sub[, start[, end]]) → int. Return the highest index in B where subsection sub is found. Raise ValueError when not found.rjust(self, width, fillchar=b' ', /) — Return a right-justified string of length width.rpartition(self, sep, /) — Partition the bytes into three parts using the given separator, starting at the end.rsplit(self, /, sep=None, maxsplit=-1) — Return a list of the sections in the bytes, using sep as the delimiter.rstrip(self, bytes=None, /) — Strip trailing bytes contained in the argument.split(self, /, sep=None, maxsplit=-1) — Return a list of the sections in the bytes, using sep as the delimiter.splitlines(self, /, keepends=False) — Return a list of the lines in the bytes, breaking at line boundaries.startswith(...) — B.startswith(prefix[, start[, end]]) → bool. Return True if B starts with the specified prefix.strip(self, bytes=None, /) — Strip leading and trailing bytes contained in the argument.swapcase(...) — B.swapcase() → copy of B. Return a copy of B with uppercase ASCII converted to lowercase and vice versa.title(...) — B.title() → copy of B. Return a titlecased version of B.translate(self, table, /, delete=b'') — Return a copy with each character mapped by the given translation table.upper(...) — B.upper() → copy of B. Return a copy of B with all ASCII characters converted to uppercase.zfill(self, width, /) — Pad a numeric string with zeros on the left.fromhex(string, /) from builtins.type — Create a bytes object from a string of hexadecimal numbers.__new__(*args, **kwargs) from builtins.type — Create and return a new object.maketrans(frm, to, /) — Return a translation table useable for the bytes or bytearray translate method.DB(*args, **kw)
Wrapper class for the _pg connection type.
__del__(self)__dir__(self) — Default dir() implementation.__enter__(self) — Enter the runtime context. This will start a transaction.__exit__(self, et, ev, tb) — Exit the runtime context. This will end the transaction.__getattr__(self, name)__init__(self, *args, **kw) — Create a new connection. You can pass either the connection parameters or an existing _pg or pgdb connection.abort = rollback(self, name=None)begin(self, mode=None) — Begin a transaction.clear(self, table, row=None) — Clear all the attributes to values determined by the types.close(self) — Close the database connection.commit(self) — Commit the current transaction.decode_json(self, s) — Decode a JSON string coming from the database.delete(self, table, row=None, **kw) — Delete an existing row in a database table.delete_prepared(self, name=None) — Delete a prepared SQL statement.describe_prepared(self, name=None) — Describe a prepared SQL statement.encode_json(self, d) — Encode a JSON string for use within SQL.end = commit(self)get(self, table, row, keyname=None) — Get a row from a database table or view.get_as_dict(self, table, keyname=None, what=None, where=None, order=None, limit=None, offset=None, scalar=False) — Get a table as a dictionary.get_as_list(self, table, what=None, where=None, order=None, limit=None, offset=None, scalar=False) — Get a table as a list.get_attnames(self, table, with_oid=True, flush=False) — Given the name of a table, dig out the set of attribute names.get_databases(self) — Get list of databases in the system.get_parameter(self, parameter) — Get the value of a run-time parameter.get_relations(self, kinds=None, system=False) — Get list of relations in connected database of specified kinds.get_tables(self, system=False) — Return list of tables in connected database.has_table_privilege(self, table, privilege='select', flush=False) — Check whether current user has specified table privilege.insert(self, table, row=None, **kw) — Insert a row into a database table.notification_handler(self, event, callback, arg_dict=None, timeout=None, stop_event=None) — Get notification handler that will run the given callback.pkey(self, table, composite=False, flush=False) — Get or set the primary key of a table.prepare(self, name, command) — Create a prepared SQL statement.query(self, command, *args) — Execute a SQL command string.query_formatted(self, command, parameters=None, types=None, inline=False) — Execute a formatted SQL command string.query_prepared(self, name, *args) — Execute a prepared SQL statement.release(self, name) — Destroy a previously defined savepoint.reopen(self) — Reopen connection to the database.reset(self) — Reset connection with current parameters.rollback(self, name=None) — Roll back the current transaction.savepoint(self, name) — Define a new savepoint within the current transaction.set_parameter(self, parameter, value=None, local=False) — Set the value of a run-time parameter.start = begin(self, mode=None)truncate(self, table, restart=False, cascade=False, > — Empty a table or set of tables.update(self, table, row=None, **kw) — Update an existing row in a database table.upsert(self, table, row=None, **kw) — Insert a row into a database table with conflict resolution.use_regtypes(self, regtypes=None) — Use registered type names instead of simplified type names.unescape_bytea(...) — unescape_bytea(string) — unescape bytea data retrieved as text__dict__ — dictionary for instance variables (if defined)__weakref__ — list of weak references to the object (if defined)db = NoneInherits from DatabaseError. Standard exception class with no additional methods beyond those inherited from builtins.Exception and builtins.BaseException.
Inherits from Error. Standard exception class with no additional methods beyond those inherited from builtins.Exception and builtins.BaseException.
Inherits from builtins.Exception. Standard exception class with __weakref__ data descriptor.
Wrapper class for marking hstore values.
__str__(self) — Return str(self).__dict__ — dictionary for instance variables (if defined)__weakref__ — list of weak references to the object (if defined)__contains__(self, key, /) — True if the dictionary has the specified key, else False.__delitem__(self, key, /) — Delete self[key].__eq__(self, value, /) — Return self==value.__ge__(self, value, /) — Return self>=value.__getattribute__(self, name, /) — Return getattr(self, name).__getitem__(...) — x.__getitem__(y) <==> x[y]__gt__(self, value, /) — Return self>value.__init__(self, /, *args, **kwargs) — Initialize self.__ior__(self, value, /) — Return self|=value.__iter__(self, /) — Implement iter(self).__le__(self, value, /) — Return self<=value.__len__(self, /) — Return len(self).__lt__(self, value, /) — Return self<value.__ne__(self, value, /) — Return self!=value.__or__(self, value, /) — Return self|value.__repr__(self, /) — Return repr(self).__reversed__(self, /) — Return a reverse iterator over the dict keys.__ror__(self, value, /) — Return value|self.__setitem__(self, key, value, /) — Set self[key] to value.__sizeof__(...) — D.__sizeof__() → size of D in memory, in bytesclear(...) — D.clear() → None. Remove all items from D.copy(...) — D.copy() → a shallow copy of Dget(self, key, default=None, /) — Return the value for key if key is in the dictionary, else default.items(...) — D.items() → a set-like object providing a view on D's itemskeys(...) — D.keys() → a set-like object providing a view on D's keyspop(...) — D.pop(k[,d]) → v, remove specified key and return the corresponding value.popitem(self, /) — Remove and return a (key, value) pair as a 2-tuple.setdefault(self, key, default=None, /) — Insert key with a value of default if key is not in the dictionary.update(...) — D.update([E, ]**F) → None. Update D from dict/iterable E and F.values(...) — D.values() → an object providing a view on D's values__class_getitem__(...) from builtins.type — See PEP 585fromkeys(iterable, value=None, /) from builtins.type — Create a new dictionary with keys from iterable and values set to value.__hash__ = NoneInherits from DatabaseError. Standard exception class with no additional methods beyond those inherited from builtins.Exception and builtins.BaseException.
Inherits from Error. Standard exception class with no additional methods beyond those inherited from builtins.Exception and builtins.BaseException.
Inherits from DatabaseError. Standard exception class with no additional methods beyond those inherited from builtins.Exception and builtins.BaseException.
Inherits from DataError. Standard exception class with no additional methods beyond those inherited from builtins.Exception and builtins.BaseException.
Json(obj)
Wrapper class for marking Json values.
__init__(self, obj) — Initialize self. See help(type(self)) for accurate signature.__dict__ — dictionary for instance variables (if defined)__weakref__ — list of weak references to the object (if defined)Wrapper class for marking literal SQL values.
__dict__ — dictionary for instance variables (if defined)__weakref__ — list of weak references to the object (if defined)__add__(self, value, /) — Return self+value.__contains__(self, key, /) — Return key in self.__eq__(self, value, /) — Return self==value.__format__(self, format_spec, /) — Return a formatted version of the string as described by format_spec.__ge__(self, value, /) — Return self>=value.__getattribute__(self, name, /) — Return getattr(self, name).__getitem__(self, key, /) — Return self[key].__getnewargs__(...)__gt__(self, value, /) — Return self>value.__hash__(self, /) — Return hash(self).__iter__(self, /) — Implement iter(self).__le__(self, value, /) — Return self<=value.__len__(self, /) — Return len(self).__lt__(self, value, /) — Return self<value.__mod__(self, value, /) — Return self%value.__mul__(self, value, /) — Return self*value.__ne__(self, value, /) — Return self!=value.__repr__(self, /) — Return repr(self).__rmod__(self, value, /) — Return value%self.__rmul__(self, value, /) — Return value*self.__sizeof__(self, /) — Return the size of the string in memory, in bytes.__str__(self, /) — Return str(self).capitalize(self, /) — Return a capitalized version of the string.casefold(self, /) — Return a version of the string suitable for caseless comparisons.center(self, width, fillchar=' ', /) — Return a centered string of length width.count(...) — S.count(sub[, start[, end]]) → int. Return the number of non-overlapping occurrences of substring sub in string S[start:end].encode(self, /, encoding='utf-8', errors='strict') — Encode the string using the codec registered for encoding.endswith(...) — S.endswith(suffix[, start[, end]]) → bool. Return True if S ends with the specified suffix.expandtabs(self, /, tabsize=8) — Return a copy where all tab characters are expanded using spaces.find(...) — S.find(sub[, start[, end]]) → int. Return the lowest index in S where substring sub is found.format(...) — S.format(*args, **kwargs) → str. Return a formatted version of S.format_map(...) — S.format_map(mapping) → str. Return a formatted version of S using substitutions from mapping.index(...) — S.index(sub[, start[, end]]) → int. Return the lowest index in S where substring sub is found. Raises ValueError when not found.isalnum(self, /) — Return True if the string is alpha-numeric.isalpha(self, /) — Return True if the string is alphabetic.isascii(self, /) — Return True if all characters in the string are ASCII.isdecimal(self, /) — Return True if the string is a decimal string.isdigit(self, /) — Return True if the string is a digit string.isidentifier(self, /) — Return True if the string is a valid Python identifier.islower(self, /) — Return True if the string is lowercase.isnumeric(self, /) — Return True if the string is numeric.isprintable(self, /) — Return True if the string is printable.isspace(self, /) — Return True if the string is whitespace.istitle(self, /) — Return True if the string is title-cased.isupper(self, /) — Return True if the string is uppercase.join(self, iterable, /) — Concatenate any number of strings.ljust(self, width, fillchar=' ', /) — Return a left-justified string of length width.lower(self, /) — Return a copy of the string converted to lowercase.lstrip(self, chars=None, /) — Return a copy of the string with leading whitespace removed.partition(self, sep, /) — Partition the string into three parts using the given separator.removeprefix(self, prefix, /) — Return a str with the given prefix string removed if present.removesuffix(self, suffix, /) — Return a str with the given suffix string removed if present.replace(self, old, new, count=-1, /) — Return a copy with all occurrences of substring old replaced by new.rfind(...) — S.rfind(sub[, start[, end]]) → int. Return the highest index in S where substring sub is found.rindex(...) — S.rindex(sub[, start[, end]]) → int. Return the highest index in S where substring sub is found. Raises ValueError when not found.rjust(self, width, fillchar=' ', /) — Return a right-justified string of length width.rpartition(self, sep, /) — Partition the string into three parts using the given separator, starting at the end.rsplit(self, /, sep=None, maxsplit=-1) — Return a list of the substrings in the string, using sep as the separator.rstrip(self, chars=None, /) — Return a copy of the string with trailing whitespace removed.split(self, /, sep=None, maxsplit=-1) — Return a list of the substrings in the string, using sep as the separator.splitlines(self, /, keepends=False) — Return a list of the lines in the string, breaking at line boundaries.startswith(...) — S.startswith(prefix[, start[, end]]) → bool. Return True if S starts with the specified prefix.strip(self, chars=None, /) — Return a copy of the string with leading and trailing whitespace removed.swapcase(self, /) — Convert uppercase characters to lowercase and lowercase characters to uppercase.title(self, /) — Return a version of the string where each word is titlecased.translate(self, table, /) — Replace each character in the string using the given translation table.upper(self, /) — Return a copy of the string converted to uppercase.zfill(self, width, /) — Pad a numeric string with zeros on the left.maketrans(...) — Return a translation table usable for str.translate().Inherits from InvalidResultError. Standard exception class with no additional methods beyond those inherited from builtins.Exception and builtins.BaseException.
Inherits from InvalidResultError. Standard exception class with no additional methods beyond those inherited from builtins.Exception and builtins.BaseException.
Inherits from DatabaseError. Standard exception class with no additional methods beyond those inherited from builtins.Exception and builtins.BaseException.
NotificationHandler(db, event, callback=None, arg_dict=None, timeout=None, stop_event=None)
A PostgreSQL client-side asynchronous notification handler.
__call__(self) — Invoke the notification handler.__del__(self)__init__(self, db, event, callback=None, arg_dict=None, timeout=None, stop_event=None) — Initialize the notification handler.close(self) — Stop listening and close the connection.listen(self) — Start listening for the event and the stop event.notify(self, db=None, stop=False, payload=None) — Generate a notification.unlisten(self) — Stop listening for the event and the stop event.__dict__ — dictionary for instance variables (if defined)__weakref__ — list of weak references to the object (if defined)Inherits from DatabaseError. Standard exception class with no additional methods beyond those inherited from builtins.Exception and builtins.BaseException.
Inherits from DatabaseError. Standard exception class with no additional methods beyond those inherited from builtins.Exception and builtins.BaseException.
Dictionary mapping database types to typecast functions.
__missing__(self, typ) — Create a cast function if it is not cached.create_array_cast(self, basecast) — Create an array typecast for the given base cast.create_record_cast(self, name, fields, casts) — Create a named record typecast for the given fields and casts.dateformat(self) — Return the current date format.get(self, typ, default=None) — Get the typecast function for the given database type.get_attnames(self, typ) — Return the fields for the given record type.reset(self, typ=None) — Reset the typecasts for the specified type(s) to their defaults.set(self, typ, cast) — Set a typecast function for the specified database type(s).get_default(typ) from builtins.type — Get the default typecast function for the given database type.set_default(typ, cast) from builtins.type — Set a default typecast function for the given database type(s).__dict__ — dictionary for instance variables (if defined)__weakref__ — list of weak references to the object (if defined)connection = Nonedefaults = {'anyarray': <built-in function cast_array>, 'bool': <funct...Inherits from builtins.Exception. Standard exception class with __weakref__ data descriptor.
cast_array(...) — cast_array(string, cast=None, delim=',') — cast a string as an arraycast_hstore(...) — cast_hstore(string) — cast a string as an hstorecast_record(...) — cast_record(string, cast=None, delim=',') — cast a string as a recordconnect(...) — connect(dbname, host, port, opt) — connect to a PostgreSQL databaseescape_bytea(...) — escape_bytea(data) — escape binary data for use within SQL as type byteaescape_string(...) — escape_string(string) — escape a string for use within SQLget_array(...) — get_array() — check whether arrays are converted as listsget_bool(...) — get_bool() — check whether boolean values are converted to boolget_bytea_escaped(...) — get_bytea_escaped() — check whether bytea will be returned escapedget_datestyle(...) — get_datestyle() — get which date style is assumedget_decimal(...) — get_decimal() — get the decimal type to be used for numeric valuesget_decimal_point(...) — get_decimal_point() — get decimal point to be used for money valuesget_defbase(...) — get_defbase() — return default database nameget_defhost(...) — get_defhost() — return default database hostget_defopt(...) — get_defopt() — return default database optionsget_defport(...) — get_defport() — return default database portget_defuser(...) — get_defuser() — return default database usernameget_jsondecode(...) — get_jsondecode() — get the function used for decoding json resultsset_array(...) — set_array(on) — set whether arrays should be converted to listsset_bool(...) — set_bool(on) — set whether boolean values should be converted to boolset_bytea_escaped(...) — set_bytea_escaped(on) — set whether bytea will be returned escapedset_datestyle(...) — set_datestyle(style) — set which style is assumedset_decimal(...) — set_decimal(cls) — set a decimal type to be used for numeric valuesset_decimal_point(...) — set_decimal_point(char) — set decimal point to be used for money valuesset_defbase(...) — set_defbase(string) — set default database name and return previous valueset_defhost(...) — set_defhost(string) — set default database host and return previous valueset_defopt(...) — set_defopt(string) — set default options and return previous valueset_defpasswd(...) — set_defpasswd(password) — set default database passwordset_defport(...) — set_defport(port) — set default port and return previous valueset_defuser(...) — set_defuser(name) — set default username and return previous valueset_jsondecode(...) — set_jsondecode(func) — set a function to be used for decoding json resultsset_query_helpers(...) — set_query_helpers(*helpers) — set internal query helper functionsunescape_bytea(...) — unescape_bytea(string) — unescape bytea data retrieved as textINV_READ = 262144INV_WRITE = 131072SEEK_CUR = 1SEEK_END = 2SEEK_SET = 0TRANS_ACTIVE = 1TRANS_IDLE = 0TRANS_INERROR = 3TRANS_INTRANS = 2TRANS_UNKNOWN = 4__all__ = ['DB', 'Adapter', 'NotificationHandler', 'Typecasts', 'Bytea...version = '5.1.2'5.1.2
/usr/lib/python3/dist-packages/pg.py
Generated by phpman v4.10.0-7-g98e9fd5 · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-09-01 16:48 @216.73.216.239
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)