9/28/2023 0 Comments Psycopg2 tutorial![]() Is closed (using the close() method) or destroyed (using del CommittedĬhanges are immediately made persistent in the database. The connection is responsible for terminating its transaction, calling either Should any commandįail, the transaction will be aborted and no further command will be executed ![]() Issued by all the cursors created by the same connection. Transaction – not only the commands issued by the first cursor, but the ones The following database commands will be executed in the context of the same Byĭefault, the first time a command is sent to the database (using one of theĬursors created by the connection), a new transaction is created. In Psycopg transactions are handled by the connection class. ForĬhanged in version 2.3: namedtuple instances are adapted like regular tuples andĬan thus be used to represent composite types. Passing a sequence of values as the second argument of the function. Passing parameters to an SQL statement happens in functions such asĬursor.execute() by using %s placeholders in the SQL statement, and Many standard Python types areĪlready adapted to the correct SQL representation. Type determines the function used to convert the object into a string Psycopg converts Python variables to SQL values using their types: the Python Using methods such as fetchone(), fetchmany(), Retrieve data from the database by iteration or Send commands to the database using methods such as execute() The class cursor allows interaction with the database: Terminate transactions using the methods commit() or It allows to:Ĭreate new cursor instances using the cursor() method to The class connection encapsulates a database session. The function connect() creates a new database session and commit () # Close communication with the database > cur. fetchone () (1, 100, "abc'def") # Make the changes to the database persistent > conn. ![]() ( 100, "abc'def" )) # Query the database and obtain data as Python objects > cur. execute ( "INSERT INTO test (num, data) VALUES ( %s, %s )". execute ( "CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar) " ) # Pass data to fill a query placeholders and let Psycopg perform # the correct conversion (no more SQL injections!) > cur. ![]() cursor () # Execute a command: this creates a new table > cur. connect ( "dbname=test user=postgres" ) # Open a cursor to perform database operations > cur = conn. import psycopg2 # Connect to an existing database > conn = psycopg2. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |