Tóm lược. trong hướng dẫn này, bạn sẽ tìm hiểu cách kết nối với máy chủ cơ sở dữ liệu PostgreSQL trong chương trình Python bằng bộ điều hợp cơ sở dữ liệu
4Code language: Shell Session [shell]
python setup.py build sudo python setup.py install
Cài đặt mô-đun psycopg2
Đầu tiên, hãy truy cập gói psycopg2 tại đây
Thứ hai, sử dụng dòng lệnh sau từ thiết bị đầu cuối
Code language: Shell Session [shell]
pip install psycopg2
Nếu bạn đã tải gói nguồn vào máy tính của mình, bạn có thể sử dụng cài đặt. py như sau
Code language: Shell Session [shell]
python setup.py build sudo python setup.py install
Tạo cơ sở dữ liệu mới
Đầu tiên, đăng nhập vào máy chủ cơ sở dữ liệu PostgreSQL bằng bất kỳ công cụ máy khách nào như pgAdmin hoặc psql
Thứ hai, sử dụng câu lệnh sau để tạo cơ sở dữ liệu mới có tên
5 trong máy chủ cơ sở dữ liệu PostgreSQLCode language: Shell Session [shell]
python setup.py build sudo python setup.py install
Code language: SQL [Structured Query Language] [sql]
CREATE DATABASE suppliers;
Kết nối với cơ sở dữ liệu PostgreSQL bằng psycopg2
Để kết nối với cơ sở dữ liệu
5, bạn sử dụng chức năngCode language: Shell Session [shell]
python setup.py build sudo python setup.py install
7 của mô-đunCode language: Shell Session [shell]
python setup.py build sudo python setup.py install
8Code language: Shell Session [shell]
python setup.py build sudo python setup.py install
Hàm
7 tạo một phiên cơ sở dữ liệu mới và trả về một thể hiện mới của lớpCode language: Shell Session [shell]
python setup.py build sudo python setup.py install
0. Bằng cách sử dụng đối tượngCode language: SQL [Structured Query Language] [sql]
CREATE DATABASE suppliers;
0, bạn có thể tạo mộtCode language: SQL [Structured Query Language] [sql]
CREATE DATABASE suppliers;
2 mới để thực thi bất kỳ câu lệnh SQL nàoCode language: SQL [Structured Query Language] [sql]
CREATE DATABASE suppliers;
Để gọi hàm
7, bạn chỉ định các tham số cơ sở dữ liệu PostgreSQL dưới dạng chuỗi kết nối và chuyển nó vào hàm như thế nàyCode language: Shell Session [shell]
python setup.py build sudo python setup.py install
Code language: SQL [Structured Query Language] [sql]
conn = psycopg2.connect["dbname=suppliers user=postgres password=postgres"]
Hoặc bạn có thể sử dụng danh sách đối số từ khóa
Code language: Python [python]
conn = psycopg2.connect[ host="localhost", database="suppliers", user="postgres", password="Abcd1234"]
Sau đây là danh sách các thông số kết nối
4. tên của cơ sở dữ liệu mà bạn muốn kết nối
Code language: SQL [Structured Query Language] [sql]CREATE DATABASE suppliers;
5. tên người dùng được sử dụng để xác thực
Code language: SQL [Structured Query Language] [sql]CREATE DATABASE suppliers;
6. mật khẩu dùng để xác thực
Code language: SQL [Structured Query Language] [sql]CREATE DATABASE suppliers;
7. địa chỉ máy chủ cơ sở dữ liệu e. g. , localhost hoặc địa chỉ IP
Code language: SQL [Structured Query Language] [sql]CREATE DATABASE suppliers;
8. số cổng mặc định là 5432 nếu không được cung cấp
Code language: SQL [Structured Query Language] [sql]CREATE DATABASE suppliers;
Để thuận tiện hơn, bạn có thể sử dụng tệp cấu hình để lưu trữ tất cả các thông số kết nối
Phần sau hiển thị nội dung của tệp
9Code language: SQL [Structured Query Language] [sql]
CREATE DATABASE suppliers;
Code language: Shell Session [shell]
[postgresql] host=localhost database=suppliers user=postgres password=SecurePas$1
Bằng cách sử dụng
9, bạn có thể thay đổi các tham số kết nối PostgreSQL khi chuyển mã sang môi trường sản xuất mà không cần sửa đổi mãCode language: SQL [Structured Query Language] [sql]
CREATE DATABASE suppliers;
Lưu ý rằng nếu bạn git, bạn cần thêm
9 vào tệpCode language: SQL [Structured Query Language] [sql]
CREATE DATABASE suppliers;
2 để không chuyển giao thông tin nhạy cảm cho repo công khai như github. TệpCode language: SQL [Structured Query Language] [sql]
conn = psycopg2.connect["dbname=suppliers user=postgres password=postgres"]
2 sẽ như thế này
conn = psycopg2.connect["dbname=suppliers user=postgres password=postgres"]
Code language: SQL [Structured Query Language] [sql]
Code language: CSS [css]
database.ini
Hàm
4 sau đây đọc tệpCode language: SQL [Structured Query Language] [sql]
conn = psycopg2.connect["dbname=suppliers user=postgres password=postgres"]
9 và trả về các tham số kết nối. HàmCode language: SQL [Structured Query Language] [sql]
CREATE DATABASE suppliers;
4 được đặt trong tệpCode language: SQL [Structured Query Language] [sql]
conn = psycopg2.connect["dbname=suppliers user=postgres password=postgres"]
7Code language: SQL [Structured Query Language] [sql]
conn = psycopg2.connect["dbname=suppliers user=postgres password=postgres"]
Code language: Python [python]
#!/usr/bin/python from configparser import ConfigParser def config[filename='database.ini', section='postgresql']: # create a parser parser = ConfigParser[] # read config file parser.read[filename] # get section, default to postgresql db = {} if parser.has_section[section]: params = parser.items[section] for param in params: db[param[0]] = param[1] else: raise Exception['Section {0} not found in the {1} file'.format[section, filename]] return db
Hàm
7 sau đây kết nối với cơ sở dữ liệuCode language: Shell Session [shell]
python setup.py build sudo python setup.py install
5 và in ra phiên bản cơ sở dữ liệu PostgreSQLCode language: Shell Session [shell]
python setup.py build sudo python setup.py install
Code language: Python [python]
#!/usr/bin/python import psycopg2 from config import config def connect[]: """ Connect to the PostgreSQL database server """ conn = None try: # read connection parameters params = config[] # connect to the PostgreSQL server print['Connecting to the PostgreSQL database...'] conn = psycopg2.connect[**params] # create a cursor cur = conn.cursor[] # execute a statement print['PostgreSQL database version:'] cur.execute['SELECT version[]'] # display the PostgreSQL database server version db_version = cur.fetchone[] print[db_version] # close the communication with the PostgreSQL cur.close[] except [Exception, psycopg2.DatabaseError] as error: print[error] finally: if conn is not None: conn.close[] print['Database connection closed.'] if __name__ == '__main__': connect[]
Làm thế nào nó hoạt động
- Đầu tiên, đọc các tham số kết nối cơ sở dữ liệu từ tệp
9
Code language: SQL [Structured Query Language] [sql]CREATE DATABASE suppliers;
- Tiếp theo, tạo một kết nối cơ sở dữ liệu mới bằng cách gọi hàm
7
Code language: Shell Session [shell]python setup.py build sudo python setup.py install
- Sau đó, tạo một
2 mới và thực thi một câu lệnh SQL để lấy phiên bản cơ sở dữ liệu PostgreSQL
Code language: SQL [Structured Query Language] [sql]CREATE DATABASE suppliers;
- Sau đó, đọc tập kết quả bằng cách gọi phương thức
3 của đối tượng con trỏ
Code language: Python [python]conn = psycopg2.connect[ host="localhost", database="suppliers", user="postgres", password="Abcd1234"]
- Cuối cùng, đóng giao tiếp với máy chủ cơ sở dữ liệu bằng cách gọi phương thức
4 của đối tượng
Code language: Python [python]conn = psycopg2.connect[ host="localhost", database="suppliers", user="postgres", password="Abcd1234"]
2 và
Code language: SQL [Structured Query Language] [sql]CREATE DATABASE suppliers;
0CREATE DATABASE suppliers;
Thực hiện kết nối. tập tin py
Để thực thi file
7 các bạn dùng lệnh sauCode language: Python [python]
conn = psycopg2.connect[ host="localhost", database="suppliers", user="postgres", password="Abcd1234"]
Code language: Shell Session [shell]
python connect.py
Bạn sẽ thấy đầu ra sau
0Code language: Shell Session [shell]
python setup.py build sudo python setup.py install
Điều đó có nghĩa là bạn đã kết nối thành công với máy chủ cơ sở dữ liệu PostgreSQL
Xử lý sự cố
Hàm
7 đưa ra ngoại lệCode language: Shell Session [shell]
python setup.py build sudo python setup.py install
9 nếu xảy ra lỗi. Để xem nó hoạt động như thế nào, bạn có thể thay đổi thông số kết nối trong tệpCode language: Python [python]
conn = psycopg2.connect[ host="localhost", database="suppliers", user="postgres", password="Abcd1234"]
9Code language: SQL [Structured Query Language] [sql]
CREATE DATABASE suppliers;
Ví dụ: nếu bạn thay đổi máy chủ thành _______21_______1, chương trình sẽ xuất ra thông báo sau
1Code language: Shell Session [shell]
python setup.py build sudo python setup.py install
Phần sau hiển thị thông báo lỗi khi bạn thay đổi cơ sở dữ liệu thành cơ sở dữ liệu không tồn tại e. g. ,
2Code language: Shell Session [shell]
[postgresql] host=localhost database=suppliers user=postgres password=SecurePas$1
2Code language: Shell Session [shell]
python setup.py build sudo python setup.py install
Nếu bạn thay đổi người dùng thành
3, nó sẽ không được xác thực thành công như sauCode language: Shell Session [shell]
[postgresql] host=localhost database=suppliers user=postgres password=SecurePas$1
3Code language: Shell Session [shell]
python setup.py build sudo python setup.py install
Trong hướng dẫn này, bạn đã học cách kết nối với máy chủ cơ sở dữ liệu PostgreSQL từ các chương trình Python