Hướng dẫn how to execute postgresql file in python - cách thực thi tệp postgresql trong python

Tôi có một lược đồ PostgreSQL được lưu trữ trong tệp .sql. Nó trông giống như:

Show
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY,
    facebook_id TEXT NOT NULL,
    name TEXT NOT NULL,
    access_token TEXT,
    created INTEGER NOT NULL
);

Làm thế nào tôi sẽ chạy lược đồ này sau khi kết nối với cơ sở dữ liệu?

Mã Python hiện tại của tôi hoạt động cho cơ sở dữ liệu SQLite:

# Create database connection
self.connection = sqlite3.connect("example.db")

# Run database schema
with self.connection as cursor:
    cursor.executescript(open("schema.sql", "r").read())

Nhưng psycopg2 không có phương pháp

# Create database connection
self.connection = sqlite3.connect("example.db")

# Run database schema
with self.connection as cursor:
    cursor.executescript(open("schema.sql", "r").read())
2 trên con trỏ. Vì vậy, làm thế nào tôi có thể đạt được điều này?

Hướng dẫn how to execute postgresql file in python - cách thực thi tệp postgresql trong python

Brian bị bỏng

Huy hiệu vàng 19.1k88 gold badges80 silver badges72 bronze badges

Đã hỏi ngày 23 tháng 6 năm 2013 lúc 13:11Jun 23, 2013 at 13:11

Linkyndylinkyndylinkyndy

16.4K18 Huy hiệu vàng110 Huy hiệu bạc189 Huy hiệu đồng18 gold badges110 silver badges189 bronze badges

Bạn chỉ có thể sử dụng

# Create database connection
self.connection = sqlite3.connect("example.db")

# Run database schema
with self.connection as cursor:
    cursor.executescript(open("schema.sql", "r").read())
3:

with self.connection as cursor:
    cursor.execute(open("schema.sql", "r").read())

Mặc dù bạn có thể muốn đặt PSYCOPG2 thành chế độ

# Create database connection
self.connection = sqlite3.connect("example.db")

# Run database schema
with self.connection as cursor:
    cursor.executescript(open("schema.sql", "r").read())
4 trước để bạn có thể sử dụng Quản lý giao dịch riêng của tập lệnh.

Thật tuyệt nếu PsyCOPG2 cung cấp một chế độ thông minh hơn nơi nó đọc tệp trong một câu lệnh và gửi nó đến DB, nhưng hiện tại không có chế độ nào như tôi biết. Nó cần một trình phân tích cú pháp khá vững chắc để thực hiện chính xác khi đối mặt với trích dẫn

# Create database connection
self.connection = sqlite3.connect("example.db")

# Run database schema
with self.connection as cursor:
    cursor.executescript(open("schema.sql", "r").read())
5 (và biến thể
# Create database connection
self.connection = sqlite3.connect("example.db")

# Run database schema
with self.connection as cursor:
    cursor.executescript(open("schema.sql", "r").read())
6 của nó trong đó deimiter có thể là bất kỳ định danh nào),
# Create database connection
self.connection = sqlite3.connect("example.db")

# Run database schema
with self.connection as cursor:
    cursor.executescript(open("schema.sql", "r").read())
7,
# Create database connection
self.connection = sqlite3.connect("example.db")

# Run database schema
with self.connection as cursor:
    cursor.executescript(open("schema.sql", "r").read())
8 chuỗi, cơ thể chức năng lồng nhau, v.v.

Lưu ý rằng điều này sẽ không hoạt động với:

  • bất cứ thứ gì chứa các lệnh
    # Create database connection
    self.connection = sqlite3.connect("example.db")
    
    # Run database schema
    with self.connection as cursor:
        cursor.executescript(open("schema.sql", "r").read())
    
    9 Backslash
  • Sao chép .. từ Stdin
  • đầu vào rất dài

... và do đó sẽ không hoạt động với các bãi rác từ

with self.connection as cursor:
    cursor.execute(open("schema.sql", "r").read())
0

Đã trả lời ngày 23 tháng 6 năm 2013 lúc 14:20Jun 23, 2013 at 14:20

Craig Ringercraig RingerCraig Ringer

293K70 Huy hiệu vàng657 Huy hiệu bạc746 Huy hiệu đồng70 gold badges657 silver badges746 bronze badges

13

Tôi không thể trả lời các bình luận về câu trả lời được chọn bằng cách thiếu danh tiếng, vì vậy tôi sẽ đưa ra câu trả lời để giúp đỡ vấn đề

with self.connection as cursor:
    cursor.execute(open("schema.sql", "r").read())
1.

Tùy thuộc vào khối lượng DB của bạn, ________ 22 đầu ra

with self.connection as cursor:
    cursor.execute(open("schema.sql", "r").read())
3S thay vì
with self.connection as cursor:
    cursor.execute(open("schema.sql", "r").read())
1S

Đã trả lời ngày 11 tháng 2 năm 2016 lúc 14:22Feb 11, 2016 at 14:22

cur.close () Conn.close ().

Psycopg2 trong Python là gì?

  • PsyCOPG2 là trình điều khiển cơ sở dữ liệu PostgreSQL, nó được sử dụng để thực hiện các hoạt động trên PostgreSQL bằng Python, nó được thiết kế cho các ứng dụng đa luồng. Các truy vấn SQL được thực thi với psycopg2 với sự trợ giúp của phương thức thực thi (). Nó được sử dụng để thực hiện truy vấn hoặc lệnh hoạt động cơ sở dữ liệu.
  • Trong bài học này, bạn sẽ học cách thực hiện truy vấn chọn PostgreSQL từ Python bằng mô -đun PsyCOPG2.

Bạn sẽ học các hoạt động chọn PostgreSQL sau đây từ Python:

Lấy tất cả các hàng từ bảng PostgreSQL bằng cách sử dụng

with self.connection as cursor:
    cursor.execute(open("schema.sql", "r").read())
5 và tìm nạp các hàng giới hạn bằng cách sử dụng
with self.connection as cursor:
    cursor.execute(open("schema.sql", "r").read())
6 và
with self.connection as cursor:
    cursor.execute(open("schema.sql", "r").read())
7.

  • Sử dụng các biến Python trong mệnh đề WHERE of a PostgreSQL Chọn truy vấn để truyền các giá trị động. and password that you need to connect PostgreSQL
  • Điều kiện tiên quyếtdatabase table from which you want to fetch data.

Trước khi thực hiện các chương trình sau, & nbsp; vui lòng đảm bảo rằng bạn có những điều sau tại chỗ: -

Tên người dùng & nbsp; và & nbsp; Mật khẩu & nbsp; mà bạn cần kết nối PostgreSQL

Hướng dẫn how to execute postgresql file in python - cách thực thi tệp postgresql trong python
Bảng cơ sở dữ liệu PostgreSQL mà bạn muốn tìm nạp dữ liệu.

Đối với bài viết này, tôi đang sử dụng một bảng ‘di động được tạo trong cơ sở dữ liệu PostgreSQL của mình.

Nếu một bảng không có trong máy chủ PostgreSQL của bạn, bạn có thể tham khảo bài viết của chúng tôi để tạo bảng PostgreSQL từ Python.

  1. Bảng di động PostgreSQL

    Các bước để thực hiện một truy vấn chọn postgresql từ python

  2. Cách chọn từ bảng PostgreSQL bằng Python

    Kết nối với PostgreSQL từ Python
    For example,

    with self.connection as cursor:
        cursor.execute(open("schema.sql", "r").read())
    
    8;. This will return row number 5.

  3. Tham khảo kết nối cơ sở dữ liệu Python PostgreSQL để kết nối với cơ sở dữ liệu PostgreSQL từ Python bằng mô -đun PsyCOPG2.

    Xác định một truy vấn chọn postgresql

  4. Tiếp theo, chuẩn bị truy vấn chọn SQL để tìm nạp các hàng từ bảng. Bạn có thể chọn tất cả hoặc các hàng giới hạn dựa trên nhu cầu của bạn. Nếu điều kiện được sử dụng, thì nó quyết định số lượng hàng để tìm nạp. Ví dụ,
    with self.connection as cursor:
        cursor.execute(open("schema.sql", "r").read())
    
    8 ;. Điều này sẽ trả lại hàng số 5.

    Nhận đối tượng con trỏ từ kết nối

  5. Tiếp theo, sử dụng phương thức
    with self.connection as cursor:
        cursor.execute(open("schema.sql", "r").read())
    
    9 để tạo đối tượng con trỏ PSYCOPG2. Phương pháp này tạo ra một đối tượng
    import psycopg2
    
    try:
        connection = psycopg2.connect(user="sysadmin",
                                      password="pynative@#29",
                                      host="127.0.0.1",
                                      port="5432",
                                      database="postgres_db")
        cursor = connection.cursor()
        postgreSQL_select_Query = "select * from mobile"
    
        cursor.execute(postgreSQL_select_Query)
        print("Selecting rows from mobile table using cursor.fetchall")
        mobile_records = cursor.fetchall()
    
        print("Print each row and it's columns values")
        for row in mobile_records:
            print("Id = ", row[0], )
            print("Model = ", row[1])
            print("Price  = ", row[2], "\n")
    
    except (Exception, psycopg2.Error) as error:
        print("Error while fetching data from PostgreSQL", error)
    
    finally:
        # closing database connection.
        if connection:
            cursor.close()
            connection.close()
            print("PostgreSQL connection is closed")
    
    0 mới.

    Thực thi truy vấn chọn bằng phương thức Execute ()

  6. Thực hiện truy vấn chọn bằng phương thức
    import psycopg2
    
    try:
        connection = psycopg2.connect(user="sysadmin",
                                      password="pynative@#29",
                                      host="127.0.0.1",
                                      port="5432",
                                      database="postgres_db")
        cursor = connection.cursor()
        postgreSQL_select_Query = "select * from mobile"
    
        cursor.execute(postgreSQL_select_Query)
        print("Selecting rows from mobile table using cursor.fetchall")
        mobile_records = cursor.fetchall()
    
        print("Print each row and it's columns values")
        for row in mobile_records:
            print("Id = ", row[0], )
            print("Model = ", row[1])
            print("Price  = ", row[2], "\n")
    
    except (Exception, psycopg2.Error) as error:
        print("Error while fetching data from PostgreSQL", error)
    
    finally:
        # closing database connection.
        if connection:
            cursor.close()
            connection.close()
            print("PostgreSQL connection is closed")
    
    1.

    Trích xuất tất cả các hàng từ một kết quả

  7. Sau khi thực hiện thành công một thao tác chọn, hãy sử dụng phương thức
    with self.connection as cursor:
        cursor.execute(open("schema.sql", "r").read())
    
    5 của đối tượng con trỏ để lấy tất cả các hàng từ kết quả truy vấn. Nó trả về một danh sách các hàng.

    Lặp lại mỗi hàng

Lặp lại một danh sách hàng bằng cách sử dụng vòng lặp

import psycopg2

try:
    connection = psycopg2.connect(user="sysadmin",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres_db")
    cursor = connection.cursor()
    postgreSQL_select_Query = "select * from mobile"

    cursor.execute(postgreSQL_select_Query)
    print("Selecting rows from mobile table using cursor.fetchall")
    mobile_records = cursor.fetchall()

    print("Print each row and it's columns values")
    for row in mobile_records:
        print("Id = ", row[0], )
        print("Model = ", row[1])
        print("Price  = ", row[2], "\n")

except (Exception, psycopg2.Error) as error:
    print("Error while fetching data from PostgreSQL", error)

finally:
    # closing database connection.
    if connection:
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")
3 và truy cập từng hàng riêng lẻ (truy cập vào mỗi dữ liệu cột của hàng bằng cách sử dụng tên cột hoặc số chỉ mục.)

Đóng đối tượng kết nối cơ sở dữ liệu và đối tượng con trỏ

import psycopg2

try:
    connection = psycopg2.connect(user="sysadmin",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres_db")
    cursor = connection.cursor()
    postgreSQL_select_Query = "select * from mobile"

    cursor.execute(postgreSQL_select_Query)
    print("Selecting rows from mobile table using cursor.fetchall")
    mobile_records = cursor.fetchall()

    print("Print each row and it's columns values")
    for row in mobile_records:
        print("Id = ", row[0], )
        print("Model = ", row[1])
        print("Price  = ", row[2], "\n")

except (Exception, psycopg2.Error) as error:
    print("Error while fetching data from PostgreSQL", error)

finally:
    # closing database connection.
    if connection:
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")

Output:

Selecting rows from mobile table using cursor.fetchall
Print each row and it's columns values

Id =  1
Model =  IPhone XS
Price  =  1000.0 

Id =  3
Model =  Google Pixel
Price  =  700.0 

Id =  2
Model =  Samsung Galaxy S9
Price  =  900.0 

Id =  4
Model =  LG
Price  =  800.0 

PostgreSQL connection is closed

Sử dụng phương thức import psycopg2 try: connection = psycopg2.connect(user="sysadmin", password="pynative@#29", host="127.0.0.1", port="5432", database="postgres_db") cursor = connection.cursor() postgreSQL_select_Query = "select * from mobile" cursor.execute(postgreSQL_select_Query) print("Selecting rows from mobile table using cursor.fetchall") mobile_records = cursor.fetchall() print("Print each row and it's columns values") for row in mobile_records: print("Id = ", row[0], ) print("Model = ", row[1]) print("Price = ", row[2], "\n") except (Exception, psycopg2.Error) as error: print("Error while fetching data from PostgreSQL", error) finally: # closing database connection. if connection: cursor.close() connection.close() print("PostgreSQL connection is closed") 4 và import psycopg2 try: connection = psycopg2.connect(user="sysadmin", password="pynative@#29", host="127.0.0.1", port="5432", database="postgres_db") cursor = connection.cursor() postgreSQL_select_Query = "select * from mobile" cursor.execute(postgreSQL_select_Query) print("Selecting rows from mobile table using cursor.fetchall") mobile_records = cursor.fetchall() print("Print each row and it's columns values") for row in mobile_records: print("Id = ", row[0], ) print("Model = ", row[1]) print("Price = ", row[2], "\n") except (Exception, psycopg2.Error) as error: print("Error while fetching data from PostgreSQL", error) finally: # closing database connection. if connection: cursor.close() connection.close() print("PostgreSQL connection is closed") 5 để đóng các kết nối mở sau khi công việc của bạn hoàn thành.

Hãy xem ví dụ ngay bây giờ.

Ví dụ để lấy một hàng từ bảng PostgreSQL bằng Fetchall ()

import psycopg2

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

        print("Using Python variable in PostgreSQL select Query")
        cursor = connection.cursor()
        postgreSQL_select_Query = "select * from mobile where id = %s"

        cursor.execute(postgreSQL_select_Query, (mobileID,))
        mobile_records = cursor.fetchall()
        for row in mobile_records:
            print("Id = ", row[0], )
            print("Model = ", row[1])
            print("Price  = ", row[2])

    except (Exception, psycopg2.Error) as error:
        print("Error fetching data from PostgreSQL table", error)

    finally:
        # closing database connection
        if connection:
            cursor.close()
            connection.close()
            print("PostgreSQL connection is closed \n")

get_mobile_details(2)
get_mobile_details(3)

Output::

Using Python variable in PostgreSQL select Query
Id =  2
Model =  Samsung Galaxy S9
Price  =  900.0
PostgreSQL connection is closed 

Using Python variable in PostgreSQL select Query
Id =  3
Model =  Google Pixel
Price  =  700.0
PostgreSQL connection is closed

Lấy một số lượng hạn chế của các hàng từ bảng PostgreSQL

Trong hầu hết các tình huống, lấy tất cả các hàng từ một bảng bằng cách sử dụng Python có thể tốn thời gian nếu bảng chứa hàng ngàn hàng.

Vì vậy, một giải pháp thay thế tốt hơn là lấy một vài hàng bằng cách sử dụng

import psycopg2

try:
    connection = psycopg2.connect(user="sysadmin",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres_db")
    cursor = connection.cursor()
    postgreSQL_select_Query = "select * from mobile"

    cursor.execute(postgreSQL_select_Query)
    print("Selecting rows from mobile table using cursor.fetchall")
    mobile_records = cursor.fetchall()

    print("Print each row and it's columns values")
    for row in mobile_records:
        print("Id = ", row[0], )
        print("Model = ", row[1])
        print("Price  = ", row[2], "\n")

except (Exception, psycopg2.Error) as error:
    print("Error while fetching data from PostgreSQL", error)

finally:
    # closing database connection.
    if connection:
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")
7.

Cú pháp của

with self.connection as cursor:
    cursor.execute(open("schema.sql", "r").read())
6.

cursor.fetchmany([size=cursor.arraysize])

Ở đây kích thước là số lượng hàng cần được truy xuất.size is the number of rows to be retrieved.

Đọc chi tiết Fetchmany ()

Thí dụ

import psycopg2

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

    print("Selecting rows from mobile table using cursor.fetchall")
    cursor = connection.cursor()
    postgreSQL_select_Query = "select * from mobile"

    cursor.execute(postgreSQL_select_Query)
    mobile_records = cursor.fetchmany(2)

    print("Fetching 2 rows")
    for row in mobile_records:
        print("Id = ", row[0], )
        print("Model = ", row[1])
        print("Price  = ", row[2], "\n")

    mobile_records = cursor.fetchmany(2)

    print("Printing next 2 rows")
    for row in mobile_records:
        print("Id = ", row[0], )
        print("Model = ", row[1])
        print("Price  = ", row[2], "\n")

except (Exception, psycopg2.Error) as error:
    print("Error while fetching data from PostgreSQL", error)

finally:
    # closing database connection.
    if connection:
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")

Output::

Selecting rows from mobile table using cursor.fetchall

Printing 2 rows

Id =  1
Model =  IPhone XS
Price  =  1000.0 

Id =  2
Model =  Samsung Galaxy S9
Price  =  900.0 

Printing next 2 rows

Id =  3
Model =  Google Pixel
Price  =  700.0 

Id =  4
Model =  LG
Price  =  800.0 

PostgreSQL connection is closed

Lấy một hàng duy nhất từ ​​kết quả truy vấn PostgreSQL

  • Sử dụng
    import psycopg2
    
    try:
        connection = psycopg2.connect(user="sysadmin",
                                      password="pynative@#29",
                                      host="127.0.0.1",
                                      port="5432",
                                      database="postgres_db")
        cursor = connection.cursor()
        postgreSQL_select_Query = "select * from mobile"
    
        cursor.execute(postgreSQL_select_Query)
        print("Selecting rows from mobile table using cursor.fetchall")
        mobile_records = cursor.fetchall()
    
        print("Print each row and it's columns values")
        for row in mobile_records:
            print("Id = ", row[0], )
            print("Model = ", row[1])
            print("Price  = ", row[2], "\n")
    
    except (Exception, psycopg2.Error) as error:
        print("Error while fetching data from PostgreSQL", error)
    
    finally:
        # closing database connection.
        if connection:
            cursor.close()
            connection.close()
            print("PostgreSQL connection is closed")
    
    9 để chỉ lấy một hàng từ bảng PostgreSQL trong Python.
  • Bạn cũng có thể sử dụng ________ 39 & nbsp; để tìm nạp hàng tiếp theo của bộ kết quả truy vấn. Phương thức này trả về một tuple tại một thời điểm.

Thí dụ

# Create database connection
self.connection = sqlite3.connect("example.db")

# Run database schema
with self.connection as cursor:
    cursor.executescript(open("schema.sql", "r").read())
0

Output:

# Create database connection
self.connection = sqlite3.connect("example.db")

# Run database schema
with self.connection as cursor:
    cursor.executescript(open("schema.sql", "r").read())
1

Lấy một hàng duy nhất từ ​​kết quả truy vấn PostgreSQL

Sử dụng

import psycopg2

try:
    connection = psycopg2.connect(user="sysadmin",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres_db")
    cursor = connection.cursor()
    postgreSQL_select_Query = "select * from mobile"

    cursor.execute(postgreSQL_select_Query)
    print("Selecting rows from mobile table using cursor.fetchall")
    mobile_records = cursor.fetchall()

    print("Print each row and it's columns values")
    for row in mobile_records:
        print("Id = ", row[0], )
        print("Model = ", row[1])
        print("Price  = ", row[2], "\n")

except (Exception, psycopg2.Error) as error:
    print("Error while fetching data from PostgreSQL", error)

finally:
    # closing database connection.
    if connection:
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")
9 để chỉ lấy một hàng từ bảng PostgreSQL trong Python.

Bạn cũng có thể sử dụng ________ 39 & nbsp; để tìm nạp hàng tiếp theo của bộ kết quả truy vấn. Phương thức này trả về một tuple tại một thời điểm.

Bước tiếp theo:

  • Để thực hành những gì bạn đã học trong bài viết này, vui lòng giải quyết một dự án tập thể dục cơ sở dữ liệu Python để thực hành và thành thạo các hoạt động của cơ sở dữ liệu Python.Topic-specific Exercises and Quizzes
  • Bài tập và câu đố Python
  • Các bài tập mã hóa miễn phí và các câu đố bao gồm các vấn đề cơ bản của Python, cấu trúc dữ liệu, phân tích dữ liệu, v.v.

Bạn có thể sử dụng postgresql trong python không?

Ngôn ngữ thủ tục PL/Python cho phép các chức năng và quy trình của 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 plpython3u.. To install PL/Python in a particular database, use CREATE EXTENSION plpython3u .

Làm thế nào gửi dữ liệu từ postgresql đến python?

Đầu tiên, kết nối với máy chủ cơ sở dữ liệu PostgreSQL bằng cách gọi hàm Connect () của mô -đun psycopg ...
Conn = psycopg2.connect (DSN) ....
Cur = Conn.Cursor () ....
cur.execute (SQL, (value1, value2)) ....
id = cur.fetchone () [0] ....
Conn.Commit () ....
cur.close () Conn.close ().

Psycopg2 trong Python là gì?

PsyCOPG2 là trình điều khiển cơ sở dữ liệu PostgreSQL, nó được sử dụng để thực hiện các hoạt động trên PostgreSQL bằng Python, nó được thiết kế cho các ứng dụng đa luồng.Các truy vấn SQL được thực thi với psycopg2 với sự trợ giúp của phương thức thực thi ().Nó được sử dụng để thực hiện truy vấn hoặc lệnh hoạt động cơ sở dữ liệu.a PostgreSQL database driver, it is used to perform operations on PostgreSQL using python, it is designed for multi-threaded applications. SQL queries are executed with psycopg2 with the help of the execute() method. It is used to Execute a database operation query or command.