Hướng dẫn how do i run a python file in postgresql? - làm cách nào để chạy một tệp python trong postgresql?

Bạn có thể cài đặt tiện ích mở rộng không? Nếu vậy, bạn có thể sử dụng tiện ích mở rộng

CREATE FUNCTION executePython()
RETURNS VOID
AS $$
#!/bin/sh
python /path/to/MyApp
$$
LANGUAGE plsh;
5

Show
CREATE FUNCTION callMyApp()
RETURNS VOID
AS $$
import subprocess
subprocess.call(['/usr/bin/python', '/path/to/MyApp'])
$$ LANGUAGE plpythonu;

CREATE TRIGGER executePython 
AFTER INSERT ON messages 
FOR EACH ROW EXECUTE PROCEDURE callMyApp();

Lưu ý rằng điều này sẽ chạy như người dùng Postgres, do đó có thể có vấn đề về quyền.

Ngoài ra còn có một tiện ích mở rộng gọi là

CREATE FUNCTION executePython()
RETURNS VOID
AS $$
#!/bin/sh
python /path/to/MyApp
$$
LANGUAGE plsh;
6, có thể được sử dụng, nhưng dường như không phải là một gói chính thức.

CREATE FUNCTION executePython()
RETURNS VOID
AS $$
#!/bin/sh
python /path/to/MyApp
$$
LANGUAGE plsh;

Bài đăng trên blog này có thể được quan tâm cho bạn.

Ngoài ra, đây gần như là một bản sao của chuỗi này có tên Run a Shell Script khi bản ghi cơ sở dữ liệu được ghi vào Postgres.

(Lưu ý: Tôi chưa kiểm tra bất kỳ mã nào trong số này.)

Tài liệu này dành cho một phiên bản không được hỗ trợ của PostgreSQL. Bạn có thể muốn xem cùng một trang cho phiên bản hiện tại hoặc một trong các phiên bản được hỗ trợ khác được liệt kê ở trên thay thế.
You may want to view the same page for the current version, or one of the other supported versions listed above instead.

Ngôn ngữ thủ tục PL/Python cho phép các hàm PostgreSQL được viết bằng ngôn ngữ Python.PL/Python procedural language allows PostgreSQL functions to be written in the Python language.

Để cài đặt PL/Python trong một cơ sở dữ liệu cụ thể, hãy sử dụng Tạo phần mở rộng plpythonu hoặc từ dòng lệnh shell sử dụng DbName createlang plpythonu (nhưng xem thêm Phần 42.1).

Mẹo: Nếu một ngôn ngữ được cài đặt vào Template1, tất cả các cơ sở dữ liệu được tạo sau đó sẽ tự động cài đặt ngôn ngữ. If a language is installed into template1, all subsequently created databases will have the language installed automatically.

Kể từ Postgresql 7.4, PL/Python chỉ có sẵn dưới dạng ngôn ngữ "không đáng tin cậy", có nghĩa là nó không cung cấp bất kỳ cách nào để hạn chế những gì người dùng có thể làm trong đó. Do đó, nó đã được đổi tên thành plpythonu. PLPython biến thể đáng tin cậy có thể trở lại trong tương lai, nếu một cơ chế thực hiện an toàn mới được phát triển trong Python. Người viết của một chức năng trong PL/Python không đáng tin cậy phải cẩn thận rằng chức năng không thể được sử dụng để làm bất cứ điều gì không mong muốn, vì nó sẽ có thể làm bất cứ điều gì có thể được thực hiện bởi người dùng đăng nhập làm quản trị viên cơ sở dữ liệu. Chỉ các siêu nhân mới có thể tạo các hàm trong các ngôn ngữ không đáng tin cậy như plpythonu.PostgreSQL 7.4, PL/Python is only available as an "untrusted" language, meaning it does not offer any way of restricting what users can do in it. It has therefore been renamed to plpythonu. The trusted variant plpython might become available again in future, if a new secure execution mechanism is developed in Python. The writer of a function in untrusted PL/Python must take care that the function cannot be used to do anything unwanted, since it will be able to do anything that could be done by a user logged in as the database administrator. Only superusers can create functions in untrusted languages such as plpythonu.

Lưu ý: Người dùng của các gói nguồn phải đặc biệt cho phép xây dựng PL/Python trong quá trình cài đặt. (Tham khảo hướng dẫn cài đặt để biết thêm thông tin.) Người dùng của các gói nhị phân có thể tìm thấy PL/Python trong một gói con riêng biệt. Users of source packages must specially enable the build of PL/Python during the installation process. (Refer to the installation instructions for more information.) Users of binary packages might find PL/Python in a separate subpackage.

Hướng dẫn Python PostgreSQL này trình bày cách sử dụng mô -đun PsyCOPG2 để kết nối với PostgreSQL và thực hiện các truy vấn SQL, hoạt động cơ sở dữ liệu. Có nhiều cách chúng tôi có thể kết nối với cơ sở dữ liệu PostgreSQL từ Python và trong hướng dẫn này, chúng tôi sẽ khám phá một số tùy chọn để xem cách đạt được điều này.Psycopg2 module to connect to PostgreSQL and perform SQL queries, database operations. There are many ways we can connect to a PostgreSQL database from Python, and in this tutorial, we’re going to explore several options to see how to achieve this.

Dưới đây là danh sách các mô -đun Python có sẵn để hoạt động với máy chủ cơ sở dữ liệu PostgreSQL.

  • CREATE FUNCTION executePython()
    RETURNS VOID
    AS $$
    #!/bin/sh
    python /path/to/MyApp
    $$
    LANGUAGE plsh;
    
    7
  • CREATE FUNCTION executePython()
    RETURNS VOID
    AS $$
    #!/bin/sh
    python /path/to/MyApp
    $$
    LANGUAGE plsh;
    
    8
  • CREATE FUNCTION executePython()
    RETURNS VOID
    AS $$
    #!/bin/sh
    python /path/to/MyApp
    $$
    LANGUAGE plsh;
    
    9
  • pip install psycopg2
    0
  • pip install psycopg2
    1
  • pip install psycopg2
    2
  • pip install psycopg2
    3. Sqlalchemy cần bất kỳ điều nào ở trên để được cài đặt riêng.

Lưu ý: & nbsp; Trên tất cả các mô -đun tuân thủ thông số kỹ thuật API cơ sở dữ liệu Python v2.0 (PEP 249). API này được thiết kế để khuyến khích và duy trì sự giống nhau giữa các mô -đun cơ sở dữ liệu Python để truy cập cơ sở dữ liệu. Nói cách khác, cú pháp, phương thức và cách truy cập cơ sở dữ liệu giống nhau trong tất cả các mô -đun trên.Above all modules adhere to Python Database API Specification v2.0 (PEP 249). This API is designed to encourage and maintain the similarity between the Python database modules to access databases. In other words, the syntax, method, and way of access the database are the same in all the above modules.

Chúng tôi gắn bó với psycopg2 vì nó được cho là mô -đun phổ biến và ổn định nhất để làm việc với postgresql. Ngoài ra, chúng tôi đang sử dụng psycopg2 để làm việc với postgresql vì những lý do sau. because it is arguably the most popular and stable module to work with PostgreSQL. Also, We are using Psycopg2 to work with PostgreSQL because of the following reasons.

  • Nó được sử dụng trong hầu hết các khung Python và Postgres.
  • Nó cũng được duy trì tích cực và hỗ trợ phiên bản chính của Python, tức là, Python 3 và Python 2.actively maintained and supports Python’s primary version, i.e., Python 3 and Python 2.
  • Nó là an toàn cho luồng và được thiết kế cho các ứng dụng đa luồng nhiều. Lưu ý, chủ đề có thể chia sẻ các kết nối.thread-safe and designed for heavily multi-threaded applications. Note, threads can share the connections.

Hướng dẫn Python PostgreSQL này chủ yếu tập trung vào các phần sau

  • Cài đặt PsyCopg2 và sử dụng API của nó để truy cập cơ sở dữ liệu PostgreSQL
  • Thực hiện chèn dữ liệu, truy xuất dữ liệu, cập nhật dữ liệu và xóa dữ liệu thông qua ứng dụng Python.
  • Tiếp theo, nó sẽ bao gồm quản lý giao dịch PostgreSQL, gộp kết nối và kỹ thuật xử lý lỗi để phát triển các chương trình Python mạnh mẽ với PostgreSQL.

Hãy để lặn ngay trong.

Cài đặt psycopg2 bằng lệnh pip

Bạn cần cài đặt phiên bản hiện tại của PSYCOPG2 (2.8.6) trên máy của bạn để sử dụng PostgreSQL từ Python. Mô -đun này có sẵn trên pypi.org.2.8.6) on your machine to use PostgreSQL from Python. This module is available on pypi.org.

Sử dụng lệnh PIP sau, bạn có thể & nbsp; cài đặt psycopg2 trên bất kỳ hệ điều hành nào, bao gồm & nbsp; windows, & nbsp; macOS, & nbsp; linux, unix và & nbsp; ubuntu.

pip install psycopg2

Bạn cũng có thể cài đặt một phiên bản cụ thể bằng cách sử dụng lệnh sau.

pip install psycopg2=2.8.6

Nếu bạn đang phải đối mặt với & nbsp; lỗi cài đặt pip như lỗi kết nối: & nbsp; . Bạn có thể giải quyết lỗi này bằng cách đặt pypi.org và file.pythonhosted.org làm máy chủ đáng tin cậy. Nếu bạn đang đối mặt với lỗi cài đặt PIP, vui lòng thử theo lệnh. like “connection error:  [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)”. You can resolve this error by setting pypi.org and files.pythonhosted.org as trusted hosts. If you are facing a pip install error Please try following the command.

python -m pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi.python.org psycopg2

Các mô -đun hiện tại & nbsp; psycopg2 & nbsp; hỗ trợ:

  • Phiên bản Python 2.7 và Python 3 phiên bản từ 3,4 đến 3,8
  • Phiên bản máy chủ PostgreSQL từ 7.4 đến 12
  • Phiên bản thư viện máy khách PostgreSQL từ 9.1

Xác minh & NBSP; Cài đặt PSYCOPG2

Bạn sẽ nhận được các tin nhắn sau sau khi chạy lệnh trên.

  • Thu thập psycopg2
  • Tải xuống PSYCOPG2-2.8.6
  • Cài đặt các gói được thu thập: PsyCopg2
  • Đã cài đặt thành công PSYCOPG2-2.8.6

Vui lòng sử dụng lệnh sau để cài đặt PsyCopg2 nếu bạn đang sử dụng Anaconda.anaconda.

conda install -c anaconda psycopg2

Kết nối cơ sở dữ liệu Python PostgreSQL

Trong phần này, chúng tôi sẽ học cách kết nối với PostgreSQL thông qua Python bằng PSYCOPG2.

Đối số cần thiết để kết nối cơ sở dữ liệu PostgreSQL từ Python

Bạn cần biết chi tiết sau đây của máy chủ PostgreSQL để thực hiện kết nối.

  • Tên người dùng: Tên người dùng bạn sử dụng để làm việc với PostgreSQL, tên người dùng mặc định cho cơ sở dữ liệu PostgreSQL là Postgres.: The username you use to work with PostgreSQL, The default username for the PostgreSQL database is Postgres.
  • Mật khẩu: Mật khẩu được cung cấp bởi người dùng tại thời điểm cài đặt PostgreSQL.: Password is given by the user at the time of installing the PostgreSQL.
  • Tên máy chủ: Đây là & NBSP; Tên máy chủ hoặc địa chỉ IP mà PostgreSQL đang chạy. Nếu bạn đang chạy trên localhost, thì bạn có thể sử dụng localhost hoặc IP của nó, tức là, 127.0.0.0: This is the server name or Ip address on which PostgreSQL is running. if you are running on localhost, then you can use localhost, or its IP, i.e., 127.0.0.0
  • Tên cơ sở dữ liệu: Tên cơ sở dữ liệu mà bạn muốn kết nối. Ở đây chúng tôi đang sử dụng cơ sở dữ liệu có tên là Postgres_db.: Database name to which you want to connect. Here we are using Database named “postgres_db“.

Cách kết nối với PostgreSQL trong Python

  1. Cài đặt mô -đun PSYCOPG2

    Cài đặt và nhập mô -đun PSYCOPG2. Nhập bằng câu lệnh

    pip install psycopg2
    4 để bạn có thể sử dụng các phương thức mô -đun này để liên lạc với cơ sở dữ liệu PostgreSQL.

  2. Sử dụng phương thức Connect ()

    Sử dụng phương thức

    pip install psycopg2
    5 với các đối số cần thiết để kết nối MySQL. Nó sẽ trả về một đối tượng
    pip install psycopg2
    6 nếu kết nối được thiết lập thành công

  3. Sử dụng phương thức con trỏ ()

    Tạo một đối tượng con trỏ bằng cách sử dụng đối tượng kết nối được trả về bởi phương thức kết nối để thực thi các truy vấn PostgreSQL từ Python.

  4. Sử dụng phương thức Execute ()

    Các phương thức

    pip install psycopg2
    7 chạy truy vấn SQL và trả về kết quả.

  5. Trích xuất kết quả bằng Fetchall ()

    Sử dụng

    pip install psycopg2
    8 hoặc
    pip install psycopg2
    9 hoặc
    pip install psycopg2=2.8.6
    0 để đọc kết quả truy vấn.

  6. Đóng con trỏ và các đối tượng kết nối

    Sử dụng phương thức

    pip install psycopg2=2.8.6
    1 và
    pip install psycopg2=2.8.6
    2 để đóng các kết nối PostgreSQL sau khi công việc của bạn hoàn thành

Hướng dẫn how do i run a python file in postgresql? - làm cách nào để chạy một tệp python trong postgresql?
Kết nối Python PostgreSQL để truy cập cơ sở dữ liệu

Ví dụ Python để kết nối cơ sở dữ liệu PostgreSQL

Để kết nối cơ sở dữ liệu PostgreSQL và thực hiện các truy vấn SQL, bạn phải biết tên cơ sở dữ liệu bạn muốn kết nối và nếu bạn chưa tạo bất kỳ cơ sở dữ liệu nào, tôi khuyên bạn nên tạo một cơ sở dữ liệu trước khi tiếp tục.

import psycopg2
from psycopg2 import Error

try:
    # Connect to an existing database
    connection = psycopg2.connect(user="postgres",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres_db")

    # Create a cursor to perform database operations
    cursor = connection.cursor()
    # Print PostgreSQL details
    print("PostgreSQL server information")
    print(connection.get_dsn_parameters(), "\n")
    # Executing a SQL query
    cursor.execute("SELECT version();")
    # Fetch result
    record = cursor.fetchone()
    print("You are connected to - ", record, "\n")

except (Exception, Error) as error:
    print("Error while connecting to PostgreSQL", error)
finally:
    if (connection):
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")

Bạn nên nhận đầu ra sau khi kết nối với PostgreSQL từ Pythonoutput after connecting to PostgreSQL from Python

PostgreSQL server information
{'user': 'postgres', 'dbname': 'python_db', 'host': '127.0.0.1', 'port': '5432', 'tty': '', 'options': '', 'sslmode': 'prefer', 'sslcompression': '0', 'krbsrvname': 'postgres', 'target_session_attrs': 'any'} 

You are connected to -  ('PostgreSQL 12.2) 
PostgreSQL connection is closed

Điểm quan trọng

  • Trong ví dụ của chúng tôi, chúng tôi đang thực hiện A & NBSP;
  • Sử dụng lớp
    pip install psycopg2=2.8.6
    4 của PsyCopg2, chúng tôi có thể xử lý mọi lỗi cơ sở dữ liệu và ngoại lệ trong khi làm việc với PostgreSQL từ Python. Sử dụng phương pháp này, chúng tôi có thể làm cho ứng dụng của chúng tôi mạnh mẽ.
  • Lớp lỗi giúp chúng tôi hiểu chi tiết lỗi. Nó trả về một thông báo lỗi và mã lỗi nếu có.
  • Chúng ta có thể tạo ra nhiều con trỏ như chúng ta muốn từ một đối tượng kết nối duy nhất. Các con trỏ được tạo từ cùng một kết nối không được cách ly, tức là, bất kỳ thay đổi nào được thực hiện đối với cơ sở dữ liệu bởi một con trỏ đều có thể nhìn thấy ngay lập tức bởi các con trỏ khác.
  • Con trỏ không an toàn bằng chỉ.
  • Chúng ta có thể truy xuất kết quả truy vấn bằng các phương thức con trỏ như
    pip install psycopg2
    9,
    pip install psycopg2=2.8.6
    0,
    pip install psycopg2=2.8.6
    7.

Thử-Except-Finally Block

  • Chúng tôi đã đặt tất cả mã của chúng tôi trong khối Expet thử để bắt các ngoại lệ và lỗi cơ sở dữ liệu có thể xảy ra trong quá trình này.

________ 38 & nbsp; và

pip install psycopg2=2.8.6
9

  • Luôn luôn là thực hành tốt để đóng con trỏ và đối tượng kết nối một khi công việc của bạn được hoàn thành để tránh các vấn đề về cơ sở dữ liệu.

Tạo bảng PostgreSQL từ Python

Phần này sẽ học cách tạo một bảng trong PostgreSQL từ Python. Trong ví dụ này, chúng tôi sẽ tạo ra một bảng di động trên mạng trong PostgreSQL.Mobile” table in PostgreSQL.

import psycopg2
from psycopg2 import Error

try:
    connection = psycopg2.connect(user="postgres",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres_db")

    cursor = connection.cursor()
    # SQL query to create a new table
    create_table_query = '''CREATE TABLE mobile
          (ID INT PRIMARY KEY     NOT NULL,
          MODEL           TEXT    NOT NULL,
          PRICE         REAL); '''
    # Execute a command: this creates a new table
    cursor.execute(create_table_query)
    connection.commit()
    print("Table created successfully in PostgreSQL ")

except (Exception, Error) as error:
    print("Error while connecting to PostgreSQL", error)
finally:
    if connection:
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")

Đầu ra

Table created successfully in PostgreSQL PostgreSQL connection is closed

Hướng dẫn how do i run a python file in postgresql? - làm cách nào để chạy một tệp python trong postgresql?
Tạo bảng PostgreSQL từ Python

Phần này sẽ học cách tạo một bảng trong PostgreSQL từ Python. Trong ví dụ này, chúng tôi sẽ tạo ra một bảng di động trên mạng trong PostgreSQL.: Note: In the end, we are committing our changes to the database using the

python -m pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi.python.org psycopg2
0 method.

Đầu ra

Lưu ý: Lưu ý: Cuối cùng, chúng tôi đang thực hiện các thay đổi của chúng tôi đối với cơ sở dữ liệu bằng phương pháp

python -m pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi.python.org psycopg2
0.

Ánh xạ giữa các loại Python và PostgreSQLCó ánh xạ mặc định được chỉ định để chuyển đổi các loại Python thành PostgreSQL tương đương và ngược lại. Bất cứ khi nào bạn thực hiện truy vấn PostgreSQL bằng cách sử dụng python sau bảng được sử dụng bởi psycopg2 để trả về kết quả trong hình thức của các đối tượng Python.
PythonPostgresql
python -m pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi.python.org psycopg2
1
python -m pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi.python.org psycopg2
1
python -m pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi.python.org psycopg2
2
python -m pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi.python.org psycopg2
3
python -m pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi.python.org psycopg2
5
python -m pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi.python.org psycopg2
6 hoặc
python -m pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi.python.org psycopg2
7
conda install -c anaconda psycopg2
0
conda install -c anaconda psycopg2
1
python -m pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi.python.org psycopg2
8
python -m pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi.python.org psycopg2
9
conda install -c anaconda psycopg2
0
conda install -c anaconda psycopg2
1
conda install -c anaconda psycopg2
2
conda install -c anaconda psycopg2
3
conda install -c anaconda psycopg2
6
conda install -c anaconda psycopg2
4
conda install -c anaconda psycopg2
4
conda install -c anaconda psycopg2
5
conda install -c anaconda psycopg2
6
conda install -c anaconda psycopg2
7
import psycopg2
from psycopg2 import Error

try:
    # Connect to an existing database
    connection = psycopg2.connect(user="postgres",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres_db")

    # Create a cursor to perform database operations
    cursor = connection.cursor()
    # Print PostgreSQL details
    print("PostgreSQL server information")
    print(connection.get_dsn_parameters(), "\n")
    # Executing a SQL query
    cursor.execute("SELECT version();")
    # Fetch result
    record = cursor.fetchone()
    print("You are connected to - ", record, "\n")

except (Exception, Error) as error:
    print("Error while connecting to PostgreSQL", error)
finally:
    if (connection):
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")
1
conda install -c anaconda psycopg2
9
conda install -c anaconda psycopg2
9
import psycopg2
from psycopg2 import Error

try:
    # Connect to an existing database
    connection = psycopg2.connect(user="postgres",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres_db")

    # Create a cursor to perform database operations
    cursor = connection.cursor()
    # Print PostgreSQL details
    print("PostgreSQL server information")
    print(connection.get_dsn_parameters(), "\n")
    # Executing a SQL query
    cursor.execute("SELECT version();")
    # Fetch result
    record = cursor.fetchone()
    print("You are connected to - ", record, "\n")

except (Exception, Error) as error:
    print("Error while connecting to PostgreSQL", error)
finally:
    if (connection):
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")
1
import psycopg2
from psycopg2 import Error

try:
    # Connect to an existing database
    connection = psycopg2.connect(user="postgres",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres_db")

    # Create a cursor to perform database operations
    cursor = connection.cursor()
    # Print PostgreSQL details
    print("PostgreSQL server information")
    print(connection.get_dsn_parameters(), "\n")
    # Executing a SQL query
    cursor.execute("SELECT version();")
    # Fetch result
    record = cursor.fetchone()
    print("You are connected to - ", record, "\n")

except (Exception, Error) as error:
    print("Error while connecting to PostgreSQL", error)
finally:
    if (connection):
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")
4
import psycopg2
from psycopg2 import Error

try:
    # Connect to an existing database
    connection = psycopg2.connect(user="postgres",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres_db")

    # Create a cursor to perform database operations
    cursor = connection.cursor()
    # Print PostgreSQL details
    print("PostgreSQL server information")
    print(connection.get_dsn_parameters(), "\n")
    # Executing a SQL query
    cursor.execute("SELECT version();")
    # Fetch result
    record = cursor.fetchone()
    print("You are connected to - ", record, "\n")

except (Exception, Error) as error:
    print("Error while connecting to PostgreSQL", error)
finally:
    if (connection):
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")
2
import psycopg2
from psycopg2 import Error

try:
    # Connect to an existing database
    connection = psycopg2.connect(user="postgres",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres_db")

    # Create a cursor to perform database operations
    cursor = connection.cursor()
    # Print PostgreSQL details
    print("PostgreSQL server information")
    print(connection.get_dsn_parameters(), "\n")
    # Executing a SQL query
    cursor.execute("SELECT version();")
    # Fetch result
    record = cursor.fetchone()
    print("You are connected to - ", record, "\n")

except (Exception, Error) as error:
    print("Error while connecting to PostgreSQL", error)
finally:
    if (connection):
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")
3
import psycopg2
from psycopg2 import Error

try:
    # Connect to an existing database
    connection = psycopg2.connect(user="postgres",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres_db")

    # Create a cursor to perform database operations
    cursor = connection.cursor()
    # Print PostgreSQL details
    print("PostgreSQL server information")
    print(connection.get_dsn_parameters(), "\n")
    # Executing a SQL query
    cursor.execute("SELECT version();")
    # Fetch result
    record = cursor.fetchone()
    print("You are connected to - ", record, "\n")

except (Exception, Error) as error:
    print("Error while connecting to PostgreSQL", error)
finally:
    if (connection):
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")
4
import psycopg2
from psycopg2 import Error

try:
    # Connect to an existing database
    connection = psycopg2.connect(user="postgres",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres_db")

    # Create a cursor to perform database operations
    cursor = connection.cursor()
    # Print PostgreSQL details
    print("PostgreSQL server information")
    print(connection.get_dsn_parameters(), "\n")
    # Executing a SQL query
    cursor.execute("SELECT version();")
    # Fetch result
    record = cursor.fetchone()
    print("You are connected to - ", record, "\n")

except (Exception, Error) as error:
    print("Error while connecting to PostgreSQL", error)
finally:
    if (connection):
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")
5
import psycopg2
from psycopg2 import Error

try:
    # Connect to an existing database
    connection = psycopg2.connect(user="postgres",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres_db")

    # Create a cursor to perform database operations
    cursor = connection.cursor()
    # Print PostgreSQL details
    print("PostgreSQL server information")
    print(connection.get_dsn_parameters(), "\n")
    # Executing a SQL query
    cursor.execute("SELECT version();")
    # Fetch result
    record = cursor.fetchone()
    print("You are connected to - ", record, "\n")

except (Exception, Error) as error:
    print("Error while connecting to PostgreSQL", error)
finally:
    if (connection):
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")
6
import psycopg2
from psycopg2 import Error

try:
    # Connect to an existing database
    connection = psycopg2.connect(user="postgres",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres_db")

    # Create a cursor to perform database operations
    cursor = connection.cursor()
    # Print PostgreSQL details
    print("PostgreSQL server information")
    print(connection.get_dsn_parameters(), "\n")
    # Executing a SQL query
    cursor.execute("SELECT version();")
    # Fetch result
    record = cursor.fetchone()
    print("You are connected to - ", record, "\n")

except (Exception, Error) as error:
    print("Error while connecting to PostgreSQL", error)
finally:
    if (connection):
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")
7
import psycopg2
from psycopg2 import Error

try:
    # Connect to an existing database
    connection = psycopg2.connect(user="postgres",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres_db")

    # Create a cursor to perform database operations
    cursor = connection.cursor()
    # Print PostgreSQL details
    print("PostgreSQL server information")
    print(connection.get_dsn_parameters(), "\n")
    # Executing a SQL query
    cursor.execute("SELECT version();")
    # Fetch result
    record = cursor.fetchone()
    print("You are connected to - ", record, "\n")

except (Exception, Error) as error:
    print("Error while connecting to PostgreSQL", error)
finally:
    if (connection):
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")
8
IN syntax
import psycopg2
from psycopg2 import Error

try:
    # Connect to an existing database
    connection = psycopg2.connect(user="postgres",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres_db")

    # Create a cursor to perform database operations
    cursor = connection.cursor()
    # Print PostgreSQL details
    print("PostgreSQL server information")
    print(connection.get_dsn_parameters(), "\n")
    # Executing a SQL query
    cursor.execute("SELECT version();")
    # Fetch result
    record = cursor.fetchone()
    print("You are connected to - ", record, "\n")

except (Exception, Error) as error:
    print("Error while connecting to PostgreSQL", error)
finally:
    if (connection):
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")
9
Cú pháp loại tổng hợp

PostgreSQL server information {'user': 'postgres', 'dbname': 'python_db', 'host': '127.0.0.1', 'port': '5432', 'tty': '', 'options': '', 'sslmode': 'prefer', 'sslcompression': '0', 'krbsrvname': 'postgres', 'target_session_attrs': 'any'} You are connected to - ('PostgreSQL 12.2) PostgreSQL connection is closed0

PostgreSQL server information
{'user': 'postgres', 'dbname': 'python_db', 'host': '127.0.0.1', 'port': '5432', 'tty': '', 'options': '', 'sslmode': 'prefer', 'sslcompression': '0', 'krbsrvname': 'postgres', 'target_session_attrs': 'any'} 

You are connected to -  ('PostgreSQL 12.2) 
PostgreSQL connection is closed
1

Hằng số và chuyển đổi số

Khi bạn cố gắng chèn các giá trị Python python -m pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi.python.org psycopg21 và PostgreSQL server information {'user': 'postgres', 'dbname': 'python_db', 'host': '127.0.0.1', 'port': '5432', 'tty': '', 'options': '', 'sslmode': 'prefer', 'sslcompression': '0', 'krbsrvname': 'postgres', 'target_session_attrs': 'any'} You are connected to - ('PostgreSQL 12.2) PostgreSQL connection is closed3 như PostgreSQL server information {'user': 'postgres', 'dbname': 'python_db', 'host': '127.0.0.1', 'port': '5432', 'tty': '', 'options': '', 'sslmode': 'prefer', 'sslcompression': '0', 'krbsrvname': 'postgres', 'target_session_attrs': 'any'} You are connected to - ('PostgreSQL 12.2) PostgreSQL connection is closed4 và PostgreSQL server information {'user': 'postgres', 'dbname': 'python_db', 'host': '127.0.0.1', 'port': '5432', 'tty': '', 'options': '', 'sslmode': 'prefer', 'sslcompression': '0', 'krbsrvname': 'postgres', 'target_session_attrs': 'any'} You are connected to - ('PostgreSQL 12.2) PostgreSQL connection is closed5 vào PostgreSQL, nó sẽ được chuyển đổi thành các chữ SQL thích hợp. Trường hợp tương tự là với các loại số Python. Nó được chuyển đổi thành các loại postgresql tương đương.

Ví dụ: khi bạn thực thi truy vấn chèn, các đối tượng số Python như

python -m pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi.python.org psycopg2
8,
PostgreSQL server information
{'user': 'postgres', 'dbname': 'python_db', 'host': '127.0.0.1', 'port': '5432', 'tty': '', 'options': '', 'sslmode': 'prefer', 'sslcompression': '0', 'krbsrvname': 'postgres', 'target_session_attrs': 'any'} 

You are connected to -  ('PostgreSQL 12.2) 
PostgreSQL connection is closed
7,
python -m pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi.python.org psycopg2
5,
PostgreSQL server information
{'user': 'postgres', 'dbname': 'python_db', 'host': '127.0.0.1', 'port': '5432', 'tty': '', 'options': '', 'sslmode': 'prefer', 'sslcompression': '0', 'krbsrvname': 'postgres', 'target_session_attrs': 'any'} 

You are connected to -  ('PostgreSQL 12.2) 
PostgreSQL connection is closed
9are được chuyển đổi thành một biểu diễn số postgreSQL. Khi bạn đọc từ bảng PostgreSQL, các loại số nguyên được chuyển đổi thành & nbsp; một
python -m pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi.python.org psycopg2
8, các loại điểm nổi được chuyển đổi thành & nbsp; a
python -m pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi.python.org psycopg2
5, số/thập phân được chuyển đổi thành & nbsp; ________ 52.mobile” table. Now let’ see how to perform insert, select, update, and delete PostgreSQL queries from Python.

Thực hiện các hoạt động PostgreSQL CRUD từ Python

Bây giờ, chúng tôi đã tạo ra một bảng di động trên mạng. Bây giờ, hãy để xem cách thực hiện chèn, chọn, cập nhật và xóa các truy vấn PostgreSQL khỏi Python.

CREATE FUNCTION executePython()
RETURNS VOID
AS $$
#!/bin/sh
python /path/to/MyApp
$$
LANGUAGE plsh;
0

Output::

CREATE FUNCTION executePython()
RETURNS VOID
AS $$
#!/bin/sh
python /path/to/MyApp
$$
LANGUAGE plsh;
1

Trong phần này, chúng tôi sẽ học cách thực hiện các hoạt động PostgreSQL CRUD từ Python.

Bây giờ, hãy để xem ví dụ.pass parameters to SQL queries.  We will learn how to use a parameterized query to pass Python variables and dynamic data into SQL queries.

  • Vui lòng tham khảo các hướng dẫn sau đây để có thêm thông tin về chèn, cập nhật và xóa dữ liệu khỏi bảng PostgreSQL bằng Python.
  • Trong hướng dẫn sau đây, chúng tôi sẽ dạy bạn cách chuyển các tham số cho các truy vấn SQL. & NBSP; Chúng tôi sẽ tìm hiểu cách sử dụng truy vấn được tham số hóa để truyền các biến python và dữ liệu động vào các truy vấn SQL.
  • Chèn dữ liệu vào bảng PostgreSQL từ Python: Tìm hiểu cách thực thi truy vấn SQL Chèn từ ứng dụng Python để thêm bản ghi vào bảng PostgreSQL.
  • Chọn dữ liệu từ bảng PostgreSQL từ Python: Tìm hiểu cách thực thi truy vấn SQL Chọn từ ứng dụng Python để tìm nạp các hàng từ bảng cơ sở dữ liệu. Chúng tôi cũng sẽ tìm hiểu cách sử dụng các phương thức Fetchall (),
    pip install psycopg2=2.8.6
    0 và
    pip install psycopg2
    9 để đọc một số lượng hạn chế từ bảng.

Cập nhật dữ liệu của bảng PostgreSQL từ Python: Tìm hiểu cách thực thi truy vấn SQL cập nhật từ ứng dụng Python để sửa đổi bản ghi bảng PostgreSQL.

Xóa dữ liệu khỏi bảng PostgreSQL khỏi Python: Tìm hiểu cách thực thi truy vấn Xóa SQL từ ứng dụng Python để xóa các bản ghi từ bảng PostgreSQL.

Làm việc với PostgreSQL Ngày và giờ ở Python

Và khi bạn thực hiện truy vấn chọn từ Python để đọc các giá trị

import psycopg2
from psycopg2 import Error

try:
    # Connect to an existing database
    connection = psycopg2.connect(user="postgres",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres_db")

    # Create a cursor to perform database operations
    cursor = connection.cursor()
    # Print PostgreSQL details
    print("PostgreSQL server information")
    print(connection.get_dsn_parameters(), "\n")
    # Executing a SQL query
    cursor.execute("SELECT version();")
    # Fetch result
    record = cursor.fetchone()
    print("You are connected to - ", record, "\n")

except (Exception, Error) as error:
    print("Error while connecting to PostgreSQL", error)
finally:
    if (connection):
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")
3 từ bảng PostgreSQL, mô -đun PsyCOPG2 đã chuyển đổi nó thành đối tượng
import psycopg2
from psycopg2 import Error

try:
    # Connect to an existing database
    connection = psycopg2.connect(user="postgres",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres_db")

    # Create a cursor to perform database operations
    cursor = connection.cursor()
    # Print PostgreSQL details
    print("PostgreSQL server information")
    print(connection.get_dsn_parameters(), "\n")
    # Executing a SQL query
    cursor.execute("SELECT version();")
    # Fetch result
    record = cursor.fetchone()
    print("You are connected to - ", record, "\n")

except (Exception, Error) as error:
    print("Error while connecting to PostgreSQL", error)
finally:
    if (connection):
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")
2.

Chúng tôi đang sử dụng bảng vật phẩm trên mạng cho bản demo này. Vui lòng sao chép và thực hiện truy vấn dưới đây trên công cụ truy vấn PostgreSQL của bạn để có dữ liệu đầy đủ cho hoạt động này.Item” table for this demo. Please copy and execute the below query on your PostgreSQL query tool to have adequate data for this operation.

CREATE FUNCTION executePython()
RETURNS VOID
AS $$
#!/bin/sh
python /path/to/MyApp
$$
LANGUAGE plsh;
2

Hãy để hiểu về kịch bản này với một ví dụ đơn giản. Ở đây chúng tôi sẽ đọc cột

import psycopg2
from psycopg2 import Error

try:
    connection = psycopg2.connect(user="postgres",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres_db")

    cursor = connection.cursor()
    # SQL query to create a new table
    create_table_query = '''CREATE TABLE mobile
          (ID INT PRIMARY KEY     NOT NULL,
          MODEL           TEXT    NOT NULL,
          PRICE         REAL); '''
    # Execute a command: this creates a new table
    cursor.execute(create_table_query)
    connection.commit()
    print("Table created successfully in PostgreSQL ")

except (Exception, Error) as error:
    print("Error while connecting to PostgreSQL", error)
finally:
    if connection:
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")
9 từ bảng PostgreSQL và chuyển đổi nó thành một đối tượng DateTime Python.

CREATE FUNCTION executePython()
RETURNS VOID
AS $$
#!/bin/sh
python /path/to/MyApp
$$
LANGUAGE plsh;
3

Output::

CREATE FUNCTION executePython()
RETURNS VOID
AS $$
#!/bin/sh
python /path/to/MyApp
$$
LANGUAGE plsh;
4

Gọi chức năng PostgreSQL và thủ tục được lưu trữ từ Python

Hàm PostgreSQL và quy trình được lưu trữ có thể thực hiện các hoạt động khác nhau, chẳng hạn như thao tác dữ liệu hoặc truy xuất dữ liệu. Chúng ta có thể thực hiện các chức năng như vậy từ Python.

Tìm hiểu cách thực hiện chức năng PostgreSQL và thủ tục được lưu trữ trong Python.

Quản lý giao dịch Python PostgreSQL

Trong bài viết này, chúng ta sẽ thấy cách quản lý các giao dịch PostgreSQL từ Python bằng PSYCOPG2.

  • Tìm hiểu cách sử dụng phương pháp
    python -m pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi.python.org psycopg2
    0 và
    Table created successfully in PostgreSQL PostgreSQL connection is closed
    1 của lớp
    Table created successfully in PostgreSQL PostgreSQL connection is closed
    2 để quản lý các giao dịch cơ sở dữ liệu và duy trì các thuộc tính axit.
  • Ngoài ra, tìm hiểu cách thay đổi mức độ cô lập giao dịch PostgreSQL từ Python.

Python Postgresql kết nối gộp

Phần này sẽ cho bạn biết nhóm kết nối là gì và làm thế nào để triển khai nhóm kết nối cơ sở dữ liệu PostgreSQL bằng PSYCOPG2 trong Python. Sử dụng PSYCOPG2, chúng tôi có thể triển khai nhóm kết nối cho các ứng dụng đơn giản cũng như đa luồng.

Sử dụng nhóm kết nối để tăng tốc độ và hiệu suất của các ứng dụng tập trung vào cơ sở dữ liệu.

Dự án tập thể dục Python PostgreSQL

Giải quyết dự án tập thể dục cơ sở dữ liệu Python miễn phí của chúng tôi để thực hành và làm chủ các hoạt động cơ sở dữ liệu PostgreSQL bằng cách sử dụng & NBSP; Python.Python database exercise project to practice and master the PostgreSQL database operations using Python.

Trong dự án tập thể dục này, chúng tôi sẽ triển khai hệ thống thông tin bệnh viện, bao gồm tất cả các hoạt động của cơ sở dữ liệu. Trong bài tập cơ sở dữ liệu Python này, chúng tôi sẽ thực hiện các hoạt động CRUD cơ sở dữ liệu từ Python. Bài tập thực hành này cũng bao gồm & nbsp; Quản lý giao dịch & nbsp; và & nbsp; kỹ thuật xử lý lỗi.Hospital Information System, which covers all database operations. In this Python database exercise, we will do database CRUD operations From Python. This practice exercise also covers transaction management and error-handling techniques.

Reference:

  • Psycopg2
  • Postgresql
  • PEP 249

Bạn có thể chạy Python trong PostgreSQL không?

Ngôn ngữ thủ tục PL/Python cho phép các hàm PostgreSQL được viết bằng ngôn ngữ Python.Để cài đặt PL/Python trong một cơ sở dữ liệu cụ thể, hãy sử dụng Tạo phần mở rộng plpythonu hoặc từ dòng lệnh shell sử dụng DbName createlang plpythonu (nhưng xem thêm Phần 42.1).. To install PL/Python in a particular database, use CREATE EXTENSION plpythonu, or from the shell command line use createlang plpythonu dbname (but see also Section 42.1).

Làm cách nào để chạy kịch bản Python từ một thủ tục được lưu trữ trong Postgres?

Các bước để gọi một thủ tục được lưu trữ sau PostgreSQL trong Python..
Conn = psycopg2.connect (DSN) ....
Cur = Conn.Cursor () ....
cur.execute ("gọi sp_name ( %s, %s);", (val1, val2)) ....
cur.execute ("gọi sp_name);") ....
Conn.Commit ();....
cur.close () Conn.close ().

Làm cách nào để kết nối với tập lệnh Python bằng PostgreSQL?

Làm thế nào để kết nối với PostgreSQL từ Python?Để kết nối với thể hiện cơ sở dữ liệu PostgreSQL từ tập lệnh Python của bạn, bạn cần sử dụng thư viện đầu nối cơ sở dữ liệu.Trong Python, bạn có một số tùy chọn mà bạn có thể chọn.Một số thư viện được viết bằng python thuần túy bao gồm PG8000 và py-postgresql.use a database connector library. In Python, you have several options that you can choose from. Some libraries that are written in pure Python include pg8000 and py-postgresql.