postgres ---docker installs postgres, python connects to the postgres database

1. Docker installs postgres

Docker is an open source containerization platform that allows developers to build, deploy and run applications in an easily portable environment. PostgreSQL is a powerful relational database that is open source software that provides high reliability, scalability, and security.

To use PostgreSQL in Docker, you can create a container through the official PostgreSQL image on Docker Hub, and then run the PostgreSQL service in it. Here are some common steps for using PostgreSQL with Docker:

1.1 Install Docker:

Follow the instructions for your operating system to install Docker. After the installation is complete, you can run the docker command in the terminal to verify that Docker is installed correctly.

1.2 Get PostgreSQL image from Docker Hub

Run the following command to grab the latest version of the PostgreSQL image from Docker Hub:

docker pull postgres

insert image description here

1.3 Create a PostgreSQL container

Run the following command to create a new PostgreSQL container. Among them, the -e parameter is used to set environment variables, the -p parameter is used to map the container port to the host port, and the -v parameter is used to mount the host directory to the directory in the container.

docker run --name my-postgres -e POSTGRES_PASSWORD=mysecretpassword 
-e ALLOW_IP_RANGE=0.0.0.0/0  -p 5432:5432 -v /my/local/path:/var/lib/postgresql/data -d postgres

In the above command, my-postgres is the name of the container, POSTGRES_PASSWORD is the PostgreSQL administrator psd, -p 5432:5432 maps port 5432 of the container to port 5432 of the host, and /my/local/path is a directory on the host (can be set by yourself), will be used for PostgreSQL data in the container.

1.4 Accessing PostgreSQL

You can now enter the running container with the following command:

docker exec -it my-postgres psql -U postgres

This will open an interactive PostgreSQL shell where you can execute SQL commands.

These are some basic steps to use PostgreSQL in Docker. You can also use other Docker commands to manage containers, such as docker stop, docker start, and docker rm, among others.

2. Python connects to postgres database

Python connects to postgresql database

Postgresql is a commonly used relational database, and postgresql is still fully open source, so let's learn together today how to connect postgresql with python.
Install psycopg

pip install psycopg2

Official document address:

https://www.psycopg.org/docs/cursor.html

Connection database operation process

For operations such as adding, deleting, and updating , the operation process is as follows:

  • connectconnect
  • Get the cursor objectcursor
  • Execute sql to get the resultexecute
  • Operation successfully executed commitcommit
  • close the connection to release resources

If it is a query , the operation process is as follows:

  • connectconnect
  • Get the cursor objectcursor
  • Execute sql to get the resultexecute
  • retrieve data
  • close the connection to release resources

The query results and other operation steps of addition, deletion and modification are the same, only the fourth step is slightly different.

2.1 connect connection

connect

psycopg2.connect(dsn=None , connection_factory=None , cursor_factory=None , async=False , \*\*kwargs)

Create a new database session and return a new connection object.
Connection parameters can be specified as a libpq connection string using the dsn parameter:

conn = psycopg2.connect("dbname=test user=postgres password=secret")

Or with a set of keyword arguments:

conn = psycopg2.connect(dbname="test", user="postgres", password="secret")

Or a mix of both, if the same parameter name is specified in both sources, the keyword parameter value will take precedence over the dsn parameter.
Note that dsn or at least one connection-related keyword argument is required.
Basic connection parameters:

  • dbname - database name
  • user - the username to use for authentication
  • password - psd for authentication
  • host - database host address
  • port - port number to connect to (default 5432)

Example:

conn = psycopg2.connect(database='test',user='postgres',password='123456',host='localhost',port='5432')

2.2 cursor

cursor

cursor ( name = None , cursor_factory = None , scrollable = None , withhold = False ) 

Returns a new cursor object using the connection.

Example:

cursor = conn.cursor()

2.3 Excute executes sql statement

Get a cursor object from the above cursor(), and use the execute method or executemany method to execute the sql statement.

cursor.execute(sql)
cursor.executemany(sql)

2.4 Submit results

If adding, deleting, or changing the data in the table, the modification must be submitted to take effect.

conn.commit()

2.5 Get data

When querying data, we need retrieval functions to obtain data. Commonly used functions are fetchone(), fetchmany(), and fetchall().

  • fetchone()
    returns a tuple containing the next row of the result set. Returns None when no data is available.
  • fetchmany([size=cursor.arraysize])
    returns a tuple, which is the result set of the next set of results. Returns an empty list when no more rows are available.
    The number of rows to fetch per call is specified by the parameter. If not given, cursor arraysize determines the number of rows to fetch.
    If no parameters are passed, only the first piece of data is returned by default. If a number is passed in the brackets, it means how many pieces of data are obtained, and the final result will return a few pieces.
  • fetchall()
    fetches all (remaining) rows of the query result, returning them as a list of tuples. Returns an empty list if there are no more records to fetch.

2.6 Closing the connection

conn.close()

example

# -*- coding: utf-8 -*-
import psycopg2
## 建立connect 连接
conn = psycopg2.connect(database='test',user='postgres',password='xxxxxx',host='localhost',port='5432')

# 游标
cur = conn.cursor()

# 执行sql
# 建表
cur.execute('create table tname(id int,name varchar);')
# 插入数据
cur.execute('insert into tname values (1,\'张三\');');
t_table=((2,'李四'),(3,'王五'))
cur.executemany('insert into tname values (%s,%s)',t_table)

# 提交数据
conn.commit()

# 关闭连接
conn.close()

The result is as follows:
insert image description here

import psycopg2
## 建立connect 连接
conn = psycopg2.connect(database='test',user='postgres',password='xxxxxx',host='localhost',port='5432')

# 游标
cur = conn.cursor()

# 执行sql
cur.execute('select * from tname;')

# 获取数据
rows = cur.fetchall()
for row in rows:
    print(row)

# 关闭连接
conn.close()

The result is as shown in the figure below:
insert image description here
Well, this article is over here.
Thank you for reading~

Guess you like

Origin blog.csdn.net/m0_46825740/article/details/131068497