
We are searching data for your request:
Upon completion, a link will appear to access the found materials.
Psycopg: Install and Import
The module we will use for this tutorial is psycopg. It is available at this link. Download and install it using the directions that come with the package.
Once it is installed, you can import it like any other module:
# libs for database interface
import psycopg
If any of your fields require a date or time, you will also want to import the datetime module, which comes standard with Python.
import datetime02of 07
Python to PostgreSQL: Open Sesame
To open a connection to a database, psycopg needs two arguments: the name of the database ('dbname') and the name of the user ('user'). The syntax for opening a connection follows this format:
= psycopg.connect('dbname=', 'user=')
For our database, we shall use the database name 'Birds' and the username 'robert'. For the connection object within the program, let's use the variable 'connection'. So, our connection command will read as follows:
connection = psycopg.connect('dbname=Birds', 'user=robert')
Naturally, this command will only work if both variables are accurate: there must be a real database named 'Birds' to which a user named 'robert' has access. If either of these conditions is not filled, Python will throw an error.
03of 07Mark Your Place in PostgreSQL With Python
Next, Python likes to be able to keep track of where it last left off in reading and writing to the database. In psycopg, this is called the cursor, but we will use the variable 'mark' for our program. So, we can then construct the following assignment:
mark = connection.cursor()04of 07
Separating PostgreSQL Form and Python Function
While some SQL insertion formats allow for understood or unstated column structure, we will be using the following template for our insert statements:
INSERT INTO
It is scandal!
What a funny message
valuable information
now one question: who will get me from under the table !?