Hướng dẫn how do i create a database in postgresql using python? - làm cách nào để tạo cơ sở dữ liệu trong postgresql bằng python?

Xem thảo luận

Cải thiện bài viết

Lưu bài viết

  • Đọc
  • Bàn luận
  • Xem thảo luận

    Cải thiện bài viết

    Lưu bài viết

    Đọc

    Bàn luận is one of the Data Definition Language ( DDL ) statements supported by the PostgreSQL Database Management System. It is used to create database in PostgreSQL. Database name should be always unique. If it already exists then it shows that the particular database already exists. 

    Trong bài viết này, chúng tôi sẽ thảo luận về cách tạo cơ sở dữ liệu trong psotgresql bằng pysopg2 trong Python. CREATE DATABASE database_name;

    Tạo cơ sở dữ liệu là một trong những câu lệnh Ngôn ngữ định nghĩa dữ liệu (DDL) được hỗ trợ bởi hệ thống quản lý cơ sở dữ liệu PostgreSQL. Nó được sử dụng để tạo cơ sở dữ liệu trong PostgreSQL. Tên cơ sở dữ liệu phải luôn luôn duy nhất. Nếu nó đã tồn tại thì nó cho thấy cơ sở dữ liệu cụ thể đã tồn tại. & NBSP;

    Python3

    Cú pháp: Tạo cơ sở dữ liệu cơ sở dữ liệu_name;

    Ví dụ: Tạo cơ sở dữ liệu bằng PysCOPG2 & NBSP;

    con = psql.connect(dbname='postgres',
          user=self.user_name, host='',
          password=self.password)
    
    cur = con.cursor()
    cur.execute("CREATE DATABASE %s  ;" % self.db_name)
    
    3
    con = psql.connect(dbname='postgres',
          user=self.user_name, host='',
          password=self.password)
    
    cur = con.cursor()
    cur.execute("CREATE DATABASE %s  ;" % self.db_name)
    
    4
    con = psql.connect(dbname='postgres',
          user=self.user_name, host='',
          password=self.password)
    
    cur = con.cursor()
    cur.execute("CREATE DATABASE %s  ;" % self.db_name)
    
    1
    con = psql.connect(dbname='postgres',
          user=self.user_name, host='',
          password=self.password)
    
    cur = con.cursor()
    cur.execute("CREATE DATABASE %s  ;" % self.db_name)
    
    6
    con = psql.connect(dbname='postgres',
          user=self.user_name, host='',
          password=self.password)
    
    cur = con.cursor()
    cur.execute("CREATE DATABASE %s  ;" % self.db_name)
    
    7

    con = psql.connect(dbname='postgres',
          user=self.user_name, host='',
          password=self.password)
    
    cur = con.cursor()
    cur.execute("CREATE DATABASE %s  ;" % self.db_name)
    
    8
    con = psql.connect(dbname='postgres',
          user=self.user_name, host='',
          password=self.password)
    
    cur = con.cursor()
    cur.execute("CREATE DATABASE %s  ;" % self.db_name)
    
    9
    con = psql.connect(dbname='postgres',
          user=self.user_name, host='',
          password=self.password)
    
    cur = con.cursor()
    cur.execute("CREATE DATABASE %s  ;" % self.db_name)
    
    1
    InternalError: CREATE DATABASE cannot run inside a transaction block
    
    1
    con = psql.connect(dbname='postgres',
          user=self.user_name, host='',
          password=self.password)
    
    cur = con.cursor()
    cur.execute("CREATE DATABASE %s  ;" % self.db_name)
    
    7

    con = psql.connect(dbname='postgres',
          user=self.user_name, host='',
          password=self.password)
    
    cur = con.cursor()
    cur.execute("CREATE DATABASE %s  ;" % self.db_name)
    
    8
    InternalError: CREATE DATABASE cannot run inside a transaction block
    
    4
    con = psql.connect(dbname='postgres',
          user=self.user_name, host='',
          password=self.password)
    
    cur = con.cursor()
    cur.execute("CREATE DATABASE %s  ;" % self.db_name)
    
    1
    InternalError: CREATE DATABASE cannot run inside a transaction block
    
    6
    con = psql.connect(dbname='postgres',
          user=self.user_name, host='',
          password=self.password)
    
    cur = con.cursor()
    cur.execute("CREATE DATABASE %s  ;" % self.db_name)
    
    7

    con = psql.connect(dbname='postgres',
          user=self.user_name, host='',
          password=self.password)
    
    cur = con.cursor()
    cur.execute("CREATE DATABASE %s  ;" % self.db_name)
    
    8
    InternalError: CREATE DATABASE cannot run inside a transaction block
    
    9
    con = psql.connect(dbname='postgres',
          user=self.user_name, host='',
          password=self.password)
    
    cur = con.cursor()
    cur.execute("CREATE DATABASE %s  ;" % self.db_name)
    
    1
    psql -postgres -U UserName
    
    1
    con = psql.connect(dbname='postgres',
          user=self.user_name, host='',
          password=self.password)
    
    cur = con.cursor()
    cur.execute("CREATE DATABASE %s  ;" % self.db_name)
    
    7

    import psycopg2

    psql -postgres -U UserName
    
    7

    con = psql.connect(dbname='postgres',
          user=self.user_name, host='',
          password=self.password)
    
    cur = con.cursor()
    cur.execute("CREATE DATABASE %s  ;" % self.db_name)
    
    0____11
    con = psql.connect(dbname='postgres',
          user=self.user_name, host='',
          password=self.password)
    
    cur = con.cursor()
    cur.execute("CREATE DATABASE %s  ;" % self.db_name)
    
    2

    con = psql.connect(dbname='postgres',
          user=self.user_name, host='',
          password=self.password)
    
    cur = con.cursor()
    cur.execute("CREATE DATABASE %s  ;" % self.db_name)
    
    8
    psql -postgres -U UserName
    
    4
    con = psql.connect(dbname='postgres',
          user=self.user_name, host='',
          password=self.password)
    
    cur = con.cursor()
    cur.execute("CREATE DATABASE %s  ;" % self.db_name)
    
    1
    psql -postgres -U UserName
    
    6

    psql -postgres -U UserName
    
    8
    con = psql.connect(dbname='postgres',
          user=self.user_name, host='',
          password=self.password)
    
    cur = con.cursor()
    cur.execute("CREATE DATABASE %s  ;" % self.db_name)
    
    1
    create database test;
    
    0

    create database test;
    
    7

    create database test;
    
    8
    create database test;
    
    9

    #!/usr/bin/python import psycopg2 from config import config def create_tables(): """ create tables in the PostgreSQL database""" commands = ( """ CREATE TABLE vendors ( vendor_id SERIAL PRIMARY KEY, vendor_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE parts ( part_id SERIAL PRIMARY KEY, part_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE part_drawings ( part_id INTEGER PRIMARY KEY, file_extension VARCHAR(5) NOT NULL, drawing_data BYTEA NOT NULL, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """, """ CREATE TABLE vendor_parts ( vendor_id INTEGER NOT NULL, part_id INTEGER NOT NULL, PRIMARY KEY (vendor_id , part_id), FOREIGN KEY (vendor_id) REFERENCES vendors (vendor_id) ON UPDATE CASCADE ON DELETE CASCADE, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """) conn = None try: # read the connection parameters params = config() # connect to the PostgreSQL server conn = psycopg2.connect(**params) cur = conn.cursor() # create table one by one for command in commands: cur.execute(command) # close communication with the PostgreSQL database server cur.close() # commit the changes conn.commit() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() if __name__ == '__main__': create_tables()

    Code language: Python (python)
    0

    #!/usr/bin/python import psycopg2 from config import config def create_tables(): """ create tables in the PostgreSQL database""" commands = ( """ CREATE TABLE vendors ( vendor_id SERIAL PRIMARY KEY, vendor_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE parts ( part_id SERIAL PRIMARY KEY, part_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE part_drawings ( part_id INTEGER PRIMARY KEY, file_extension VARCHAR(5) NOT NULL, drawing_data BYTEA NOT NULL, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """, """ CREATE TABLE vendor_parts ( vendor_id INTEGER NOT NULL, part_id INTEGER NOT NULL, PRIMARY KEY (vendor_id , part_id), FOREIGN KEY (vendor_id) REFERENCES vendors (vendor_id) ON UPDATE CASCADE ON DELETE CASCADE, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """) conn = None try: # read the connection parameters params = config() # connect to the PostgreSQL server conn = psycopg2.connect(**params) cur = conn.cursor() # create table one by one for command in commands: cur.execute(command) # close communication with the PostgreSQL database server cur.close() # commit the changes conn.commit() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() if __name__ == '__main__': create_tables()

    Code language: Python (python)
    1

    #!/usr/bin/python import psycopg2 from config import config def create_tables(): """ create tables in the PostgreSQL database""" commands = ( """ CREATE TABLE vendors ( vendor_id SERIAL PRIMARY KEY, vendor_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE parts ( part_id SERIAL PRIMARY KEY, part_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE part_drawings ( part_id INTEGER PRIMARY KEY, file_extension VARCHAR(5) NOT NULL, drawing_data BYTEA NOT NULL, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """, """ CREATE TABLE vendor_parts ( vendor_id INTEGER NOT NULL, part_id INTEGER NOT NULL, PRIMARY KEY (vendor_id , part_id), FOREIGN KEY (vendor_id) REFERENCES vendors (vendor_id) ON UPDATE CASCADE ON DELETE CASCADE, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """) conn = None try: # read the connection parameters params = config() # connect to the PostgreSQL server conn = psycopg2.connect(**params) cur = conn.cursor() # create table one by one for command in commands: cur.execute(command) # close communication with the PostgreSQL database server cur.close() # commit the changes conn.commit() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() if __name__ == '__main__': create_tables()

    Code language: Python (python)
    2

    create database test;
    
    1
    con = psql.connect(dbname='postgres',
          user=self.user_name, host='',
          password=self.password)
    
    cur = con.cursor()
    cur.execute("CREATE DATABASE %s  ;" % self.db_name)
    
    1
    create database test;
    
    3

    Database has been created successfully !!

    create database test;
    
    4
    con = psql.connect(dbname='postgres',
          user=self.user_name, host='',
          password=self.password)
    
    cur = con.cursor()
    cur.execute("CREATE DATABASE %s  ;" % self.db_name)
    
    1
    create database test;
    
    6
    PostgreSQL:

    Hướng dẫn how do i create a database in postgresql using python? - làm cách nào để tạo cơ sở dữ liệu trong postgresql bằng python?

    # ----- ví dụ chương trình Python để tạo cơ sở dữ liệu trong PostgreSQL & NBSP; sử dụng psycopg2 -----

    # Nhập máy khách PostgreSQL cho Python

    Nhập PSYCOPG2

    từ psycopg2.Extensions nhập khẩu solation_level_autocommit

    # Kết nối với PostgreSQL DBMS

    con = psycopg2.connect ("user = test password = 'test'");

    con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT);

    # Có được một con trỏ DB

    con trỏ & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; = con.cursor ();

    name_database & nbsp; & nbsp; = "SocialMedia";

    # Tạo câu lệnh bảng

    sqlCreatedatabase = "Tạo cơ sở dữ liệu"+name_database+";"

    # Tạo bảng trong cơ sở dữ liệu PostgreSQL

    cursor.execute(sqlCreateDatabase);

    Tôi muốn tạo cơ sở dữ liệu Postgres bằng Python.

    con = psql.connect(dbname='postgres',
          user=self.user_name, host='',
          password=self.password)
    
    cur = con.cursor()
    cur.execute("CREATE DATABASE %s  ;" % self.db_name)
    

    Tôi nhận được lỗi sau:

    InternalError: CREATE DATABASE cannot run inside a transaction block
    

    Tôi đang sử dụng psycopg2 để kết nối. Tôi không hiểu vấn đề là gì. Tôi đang cố gắng làm gì là kết nối với cơ sở dữ liệu (Postgres):

    psql -postgres -U UserName
    

    Và sau đó tạo một cơ sở dữ liệu khác:

    create database test;
    

    Đây là những gì tôi thường làm và tôi muốn tự động hóa điều này bằng cách tạo tập lệnh Python.

    Tóm tắt: Trong hướng dẫn này, bạn sẽ tìm hiểu cách tạo các bảng mới trong cơ sở dữ liệu PostgreSQL bằng Python.: in this tutorial, you will learn how to create new tables in the PostgreSQL database using Python.

    Hướng dẫn này giả định rằng bạn biết cách viết

    #!/usr/bin/python import psycopg2 from config import config def create_tables(): """ create tables in the PostgreSQL database""" commands = ( """ CREATE TABLE vendors ( vendor_id SERIAL PRIMARY KEY, vendor_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE parts ( part_id SERIAL PRIMARY KEY, part_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE part_drawings ( part_id INTEGER PRIMARY KEY, file_extension VARCHAR(5) NOT NULL, drawing_data BYTEA NOT NULL, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """, """ CREATE TABLE vendor_parts ( vendor_id INTEGER NOT NULL, part_id INTEGER NOT NULL, PRIMARY KEY (vendor_id , part_id), FOREIGN KEY (vendor_id) REFERENCES vendors (vendor_id) ON UPDATE CASCADE ON DELETE CASCADE, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """) conn = None try: # read the connection parameters params = config() # connect to the PostgreSQL server conn = psycopg2.connect(**params) cur = conn.cursor() # create table one by one for command in commands: cur.execute(command) # close communication with the PostgreSQL database server cur.close() # commit the changes conn.commit() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() if __name__ == '__main__': create_tables()

    Code language: Python (python)
    3Statement. Nếu đây không phải là trường hợp, bạn nên xem hướng dẫn

    #!/usr/bin/python import psycopg2 from config import config def create_tables(): """ create tables in the PostgreSQL database""" commands = ( """ CREATE TABLE vendors ( vendor_id SERIAL PRIMARY KEY, vendor_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE parts ( part_id SERIAL PRIMARY KEY, part_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE part_drawings ( part_id INTEGER PRIMARY KEY, file_extension VARCHAR(5) NOT NULL, drawing_data BYTEA NOT NULL, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """, """ CREATE TABLE vendor_parts ( vendor_id INTEGER NOT NULL, part_id INTEGER NOT NULL, PRIMARY KEY (vendor_id , part_id), FOREIGN KEY (vendor_id) REFERENCES vendors (vendor_id) ON UPDATE CASCADE ON DELETE CASCADE, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """) conn = None try: # read the connection parameters params = config() # connect to the PostgreSQL server conn = psycopg2.connect(**params) cur = conn.cursor() # create table one by one for command in commands: cur.execute(command) # close communication with the PostgreSQL database server cur.close() # commit the changes conn.commit() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() if __name__ == '__main__': create_tables()

    Code language: Python (python)
    3.

    Các bước để tạo bảng PostgreSQL trong Python

    Để tạo một bảng mới trong cơ sở dữ liệu PostgreSQL, bạn sử dụng các bước sau:

    1. Đầu tiên, xây dựng tạo câu lệnh bảng.
    2. Tiếp theo, kết nối với cơ sở dữ liệu PostgreSQL bằng cách gọi hàm

      #!/usr/bin/python import psycopg2 from config import config def create_tables(): """ create tables in the PostgreSQL database""" commands = ( """ CREATE TABLE vendors ( vendor_id SERIAL PRIMARY KEY, vendor_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE parts ( part_id SERIAL PRIMARY KEY, part_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE part_drawings ( part_id INTEGER PRIMARY KEY, file_extension VARCHAR(5) NOT NULL, drawing_data BYTEA NOT NULL, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """, """ CREATE TABLE vendor_parts ( vendor_id INTEGER NOT NULL, part_id INTEGER NOT NULL, PRIMARY KEY (vendor_id , part_id), FOREIGN KEY (vendor_id) REFERENCES vendors (vendor_id) ON UPDATE CASCADE ON DELETE CASCADE, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """) conn = None try: # read the connection parameters params = config() # connect to the PostgreSQL server conn = psycopg2.connect(**params) cur = conn.cursor() # create table one by one for command in commands: cur.execute(command) # close communication with the PostgreSQL database server cur.close() # commit the changes conn.commit() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() if __name__ == '__main__': create_tables()

      Code language: Python (python)
      5. Hàm

      #!/usr/bin/python import psycopg2 from config import config def create_tables(): """ create tables in the PostgreSQL database""" commands = ( """ CREATE TABLE vendors ( vendor_id SERIAL PRIMARY KEY, vendor_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE parts ( part_id SERIAL PRIMARY KEY, part_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE part_drawings ( part_id INTEGER PRIMARY KEY, file_extension VARCHAR(5) NOT NULL, drawing_data BYTEA NOT NULL, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """, """ CREATE TABLE vendor_parts ( vendor_id INTEGER NOT NULL, part_id INTEGER NOT NULL, PRIMARY KEY (vendor_id , part_id), FOREIGN KEY (vendor_id) REFERENCES vendors (vendor_id) ON UPDATE CASCADE ON DELETE CASCADE, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """) conn = None try: # read the connection parameters params = config() # connect to the PostgreSQL server conn = psycopg2.connect(**params) cur = conn.cursor() # create table one by one for command in commands: cur.execute(command) # close communication with the PostgreSQL database server cur.close() # commit the changes conn.commit() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() if __name__ == '__main__': create_tables()

      Code language: Python (python)
      5 trả về một đối tượng

      #!/usr/bin/python import psycopg2 from config import config def create_tables(): """ create tables in the PostgreSQL database""" commands = ( """ CREATE TABLE vendors ( vendor_id SERIAL PRIMARY KEY, vendor_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE parts ( part_id SERIAL PRIMARY KEY, part_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE part_drawings ( part_id INTEGER PRIMARY KEY, file_extension VARCHAR(5) NOT NULL, drawing_data BYTEA NOT NULL, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """, """ CREATE TABLE vendor_parts ( vendor_id INTEGER NOT NULL, part_id INTEGER NOT NULL, PRIMARY KEY (vendor_id , part_id), FOREIGN KEY (vendor_id) REFERENCES vendors (vendor_id) ON UPDATE CASCADE ON DELETE CASCADE, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """) conn = None try: # read the connection parameters params = config() # connect to the PostgreSQL server conn = psycopg2.connect(**params) cur = conn.cursor() # create table one by one for command in commands: cur.execute(command) # close communication with the PostgreSQL database server cur.close() # commit the changes conn.commit() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() if __name__ == '__main__': create_tables()

      Code language: Python (python)
      7.
    3. Sau đó, tạo đối tượng ________ 58 & nbsp; bằng cách gọi phương thức

      #!/usr/bin/python import psycopg2 from config import config def create_tables(): """ create tables in the PostgreSQL database""" commands = ( """ CREATE TABLE vendors ( vendor_id SERIAL PRIMARY KEY, vendor_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE parts ( part_id SERIAL PRIMARY KEY, part_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE part_drawings ( part_id INTEGER PRIMARY KEY, file_extension VARCHAR(5) NOT NULL, drawing_data BYTEA NOT NULL, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """, """ CREATE TABLE vendor_parts ( vendor_id INTEGER NOT NULL, part_id INTEGER NOT NULL, PRIMARY KEY (vendor_id , part_id), FOREIGN KEY (vendor_id) REFERENCES vendors (vendor_id) ON UPDATE CASCADE ON DELETE CASCADE, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """) conn = None try: # read the connection parameters params = config() # connect to the PostgreSQL server conn = psycopg2.connect(**params) cur = conn.cursor() # create table one by one for command in commands: cur.execute(command) # close communication with the PostgreSQL database server cur.close() # commit the changes conn.commit() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() if __name__ == '__main__': create_tables()

      Code language: Python (python)
      9 của đối tượng

      #!/usr/bin/python import psycopg2 from config import config def create_tables(): """ create tables in the PostgreSQL database""" commands = ( """ CREATE TABLE vendors ( vendor_id SERIAL PRIMARY KEY, vendor_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE parts ( part_id SERIAL PRIMARY KEY, part_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE part_drawings ( part_id INTEGER PRIMARY KEY, file_extension VARCHAR(5) NOT NULL, drawing_data BYTEA NOT NULL, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """, """ CREATE TABLE vendor_parts ( vendor_id INTEGER NOT NULL, part_id INTEGER NOT NULL, PRIMARY KEY (vendor_id , part_id), FOREIGN KEY (vendor_id) REFERENCES vendors (vendor_id) ON UPDATE CASCADE ON DELETE CASCADE, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """) conn = None try: # read the connection parameters params = config() # connect to the PostgreSQL server conn = psycopg2.connect(**params) cur = conn.cursor() # create table one by one for command in commands: cur.execute(command) # close communication with the PostgreSQL database server cur.close() # commit the changes conn.commit() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() if __name__ == '__main__': create_tables()

      Code language: Python (python)
      7.
    4. Sau đó, thực hiện

      #!/usr/bin/python import psycopg2 from config import config def create_tables(): """ create tables in the PostgreSQL database""" commands = ( """ CREATE TABLE vendors ( vendor_id SERIAL PRIMARY KEY, vendor_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE parts ( part_id SERIAL PRIMARY KEY, part_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE part_drawings ( part_id INTEGER PRIMARY KEY, file_extension VARCHAR(5) NOT NULL, drawing_data BYTEA NOT NULL, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """, """ CREATE TABLE vendor_parts ( vendor_id INTEGER NOT NULL, part_id INTEGER NOT NULL, PRIMARY KEY (vendor_id , part_id), FOREIGN KEY (vendor_id) REFERENCES vendors (vendor_id) ON UPDATE CASCADE ON DELETE CASCADE, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """) conn = None try: # read the connection parameters params = config() # connect to the PostgreSQL server conn = psycopg2.connect(**params) cur = conn.cursor() # create table one by one for command in commands: cur.execute(command) # close communication with the PostgreSQL database server cur.close() # commit the changes conn.commit() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() if __name__ == '__main__': create_tables()

      Code language: Python (python)
      3 bằng cách gọi phương thức

      python create_table.py

      Code language: CSS (css)
      2 của đối tượng

      #!/usr/bin/python import psycopg2 from config import config def create_tables(): """ create tables in the PostgreSQL database""" commands = ( """ CREATE TABLE vendors ( vendor_id SERIAL PRIMARY KEY, vendor_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE parts ( part_id SERIAL PRIMARY KEY, part_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE part_drawings ( part_id INTEGER PRIMARY KEY, file_extension VARCHAR(5) NOT NULL, drawing_data BYTEA NOT NULL, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """, """ CREATE TABLE vendor_parts ( vendor_id INTEGER NOT NULL, part_id INTEGER NOT NULL, PRIMARY KEY (vendor_id , part_id), FOREIGN KEY (vendor_id) REFERENCES vendors (vendor_id) ON UPDATE CASCADE ON DELETE CASCADE, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """) conn = None try: # read the connection parameters params = config() # connect to the PostgreSQL server conn = psycopg2.connect(**params) cur = conn.cursor() # create table one by one for command in commands: cur.execute(command) # close communication with the PostgreSQL database server cur.close() # commit the changes conn.commit() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() if __name__ == '__main__': create_tables()

      Code language: Python (python)
      8.
    5. Cuối cùng, đóng giao tiếp với máy chủ cơ sở dữ liệu PostgreSQL bằng cách gọi các phương thức

      python create_table.py

      Code language: CSS (css)
      4 của các đối tượng

      #!/usr/bin/python import psycopg2 from config import config def create_tables(): """ create tables in the PostgreSQL database""" commands = ( """ CREATE TABLE vendors ( vendor_id SERIAL PRIMARY KEY, vendor_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE parts ( part_id SERIAL PRIMARY KEY, part_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE part_drawings ( part_id INTEGER PRIMARY KEY, file_extension VARCHAR(5) NOT NULL, drawing_data BYTEA NOT NULL, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """, """ CREATE TABLE vendor_parts ( vendor_id INTEGER NOT NULL, part_id INTEGER NOT NULL, PRIMARY KEY (vendor_id , part_id), FOREIGN KEY (vendor_id) REFERENCES vendors (vendor_id) ON UPDATE CASCADE ON DELETE CASCADE, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """) conn = None try: # read the connection parameters params = config() # connect to the PostgreSQL server conn = psycopg2.connect(**params) cur = conn.cursor() # create table one by one for command in commands: cur.execute(command) # close communication with the PostgreSQL database server cur.close() # commit the changes conn.commit() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() if __name__ == '__main__': create_tables()

      Code language: Python (python)
      8 và

      #!/usr/bin/python import psycopg2 from config import config def create_tables(): """ create tables in the PostgreSQL database""" commands = ( """ CREATE TABLE vendors ( vendor_id SERIAL PRIMARY KEY, vendor_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE parts ( part_id SERIAL PRIMARY KEY, part_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE part_drawings ( part_id INTEGER PRIMARY KEY, file_extension VARCHAR(5) NOT NULL, drawing_data BYTEA NOT NULL, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """, """ CREATE TABLE vendor_parts ( vendor_id INTEGER NOT NULL, part_id INTEGER NOT NULL, PRIMARY KEY (vendor_id , part_id), FOREIGN KEY (vendor_id) REFERENCES vendors (vendor_id) ON UPDATE CASCADE ON DELETE CASCADE, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """) conn = None try: # read the connection parameters params = config() # connect to the PostgreSQL server conn = psycopg2.connect(**params) cur = conn.cursor() # create table one by one for command in commands: cur.execute(command) # close communication with the PostgreSQL database server cur.close() # commit the changes conn.commit() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() if __name__ == '__main__': create_tables()

      Code language: Python (python)
      7.

    Tạo bảng trong ví dụ Python

    1) Tạo chương trình Python

    Đầu tiên, tạo một tệp mới có tên

    python create_table.py

    Code language: CSS (css)
    7.

    Thứ hai, bên trong tệp

    python create_table.py

    Code language: CSS (css)
    7, xác định một hàm mới gọi là

    python create_table.py

    Code language: CSS (css)
    9.

    Hàm

    python create_table.py

    Code language: CSS (css)
    9 tạo ra bốn bảng trong cơ sở dữ liệu

    suppliers=# \dt List of relations Schema | Name | Type | Owner --------+---------------+-------+---------- public | part_drawings | table | postgres public | parts | table | postgres public | vendor_parts | table | postgres public | vendors | table | postgres (4 rows)

    Code language: PHP (php)
    1:

    suppliers=# \dt List of relations Schema | Name | Type | Owner --------+---------------+-------+---------- public | part_drawings | table | postgres public | parts | table | postgres public | vendor_parts | table | postgres public | vendors | table | postgres (4 rows)

    Code language: PHP (php)
    2,

    suppliers=# \dt List of relations Schema | Name | Type | Owner --------+---------------+-------+---------- public | part_drawings | table | postgres public | parts | table | postgres public | vendor_parts | table | postgres public | vendors | table | postgres (4 rows)

    Code language: PHP (php)
    3,

    suppliers=# \dt List of relations Schema | Name | Type | Owner --------+---------------+-------+---------- public | part_drawings | table | postgres public | parts | table | postgres public | vendor_parts | table | postgres public | vendors | table | postgres (4 rows)

    Code language: PHP (php)
    4 và

    suppliers=# \dt List of relations Schema | Name | Type | Owner --------+---------------+-------+---------- public | part_drawings | table | postgres public | parts | table | postgres public | vendor_parts | table | postgres public | vendors | table | postgres (4 rows)

    Code language: PHP (php)
    5.

    Hướng dẫn how do i create a database in postgresql using python? - làm cách nào để tạo cơ sở dữ liệu trong postgresql bằng python?

    #!/usr/bin/python import psycopg2 from config import config def create_tables(): """ create tables in the PostgreSQL database""" commands = ( """ CREATE TABLE vendors ( vendor_id SERIAL PRIMARY KEY, vendor_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE parts ( part_id SERIAL PRIMARY KEY, part_name VARCHAR(255) NOT NULL ) """, """ CREATE TABLE part_drawings ( part_id INTEGER PRIMARY KEY, file_extension VARCHAR(5) NOT NULL, drawing_data BYTEA NOT NULL, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """, """ CREATE TABLE vendor_parts ( vendor_id INTEGER NOT NULL, part_id INTEGER NOT NULL, PRIMARY KEY (vendor_id , part_id), FOREIGN KEY (vendor_id) REFERENCES vendors (vendor_id) ON UPDATE CASCADE ON DELETE CASCADE, FOREIGN KEY (part_id) REFERENCES parts (part_id) ON UPDATE CASCADE ON DELETE CASCADE ) """) conn = None try: # read the connection parameters params = config() # connect to the PostgreSQL server conn = psycopg2.connect(**params) cur = conn.cursor() # create table one by one for command in commands: cur.execute(command) # close communication with the PostgreSQL database server cur.close() # commit the changes conn.commit() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() if __name__ == '__main__': create_tables()

    Code language: Python (python)

    2) Thực hiện chương trình Python

    Để thực hiện chương trình Python, bạn sử dụng lệnh sau:

    python create_table.py

    Code language: CSS (css)

    3) Xác minh việc tạo bảng

    Đầu tiên, đăng nhập vào máy chủ cơ sở dữ liệu PostgreSQL bằng chương trình PSQL.

    Thứ hai, sử dụng lệnh

    suppliers=# \dt List of relations Schema | Name | Type | Owner --------+---------------+-------+---------- public | part_drawings | table | postgres public | parts | table | postgres public | vendor_parts | table | postgres public | vendors | table | postgres (4 rows)

    Code language: PHP (php)
    6 để hiển thị danh sách bảng từ cơ sở dữ liệu

    suppliers=# \dt List of relations Schema | Name | Type | Owner --------+---------------+-------+---------- public | part_drawings | table | postgres public | parts | table | postgres public | vendor_parts | table | postgres public | vendors | table | postgres (4 rows)

    Code language: PHP (php)
    1.

    suppliers=# \dt List of relations Schema | Name | Type | Owner --------+---------------+-------+---------- public | part_drawings | table | postgres public | parts | table | postgres public | vendor_parts | table | postgres public | vendors | table | postgres (4 rows)

    Code language: PHP (php)

    Như bạn thấy có thể thấy rõ từ đầu ra, chúng tôi có bốn bảng được tạo thành công trong cơ sở dữ liệu

    suppliers=# \dt List of relations Schema | Name | Type | Owner --------+---------------+-------+---------- public | part_drawings | table | postgres public | parts | table | postgres public | vendor_parts | table | postgres public | vendors | table | postgres (4 rows)

    Code language: PHP (php)
    1.

    Nếu bạn sử dụng công cụ máy khách khác như PGADMIN, bạn có thể xem các bảng thông qua danh sách bảng trong lược đồ

    suppliers=# \dt List of relations Schema | Name | Type | Owner --------+---------------+-------+---------- public | part_drawings | table | postgres public | parts | table | postgres public | vendor_parts | table | postgres public | vendors | table | postgres (4 rows)

    Code language: PHP (php)
    9.

    Trong hướng dẫn này, bạn đã học từng bước làm thế nào để tạo các bảng PostgreSQL mới trong Python bằng bộ điều hợp cơ sở dữ liệu PSYCOPG.

    Hướng dẫn này có hữu ích không?

    Tôi có thể tạo cơ sở dữ liệu trong Python không?

    Giới thiệu. SQLalchemy là một thư viện Python để triển khai cơ sở dữ liệu SQL mà không cần sử dụng chính ngôn ngữ SQL. Nói cách khác, tất cả những gì bạn cần làm là triển khai cơ sở dữ liệu của mình bằng ngôn ngữ Python.SQLAlchemy is a Python library for implementing SQL databases without using the SQL language itself. In other words, all you need to do is to implement your database using the Python language.

    Làm thế nào để Python kết nối với cơ sở dữ liệu PostgreSQL?

    Thiết lập kết nối bằng Python, bạn có thể tạo các kết nối mới bằng hàm Connect ().Điều này chấp nhận các tham số kết nối cơ bản như dbname, người dùng, mật khẩu, máy chủ, cổng và trả về một đối tượng kết nối.Sử dụng chức năng này, bạn có thể thiết lập kết nối với PostgreSQL.create new connections using the connect() function. This accepts the basic connection parameters such as dbname, user, password, host, port and returns a connection object. Using this function, you can establish a connection with the PostgreSQL.

    Python có hoạt động với postgresql 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..

    Làm cách nào để tạo cơ sở dữ liệu trong PostgreSQL PGADMIN?

    Sử dụng GUI chạy pgadmin.Nhấp chuột phải vào các máy chủ mục, chọn Tạo -> Máy chủ và cung cấp kết nối với phiên bản PostgreSQL của bạn được thiết lập ở Bước 1. Trong thiết lập PostgreSQL mặc định, người dùng quản trị viên có mật khẩu trống.Trong tab Kết nối, hãy chắc chắn có máy chủ được đặt thành LocalHost.Right-click on the item Servers , select Create -> Server and provide the connection to your PostgreSQL instance set up in step 1. In the default PostgreSQL setup, the administrator user is postgres with an empty password. In the connection tab be sure to have the host set to localhost .