怎么查数据库名称(用Python如何查询已经创建的数据库?)

要查询已经创建的数据库,您需要知道使用的数据库管理系统(例如MySQL、PostgreSQL、SQL Server等)。

以下是使用Python查询不同数据库的示例

MySQL示例(使用mysql-connector-python库):

import mysql.connector

def create_conn(host, user, password, database):
    connection = mysql.connector.connect(
        host=host,
        user=user,
        password=password,
        database=database
    )
    return connection

def query_database(connection):
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM your_table_name")

    rows = cursor.fetchall()
    for row in rows:
        print(row)

    cursor.close()

if __name__ == "__main__":
    host = "localhost"
    user = "your_username"
    password = "your_password"
    database = "your_database"

    conn = create_conn(host, user, password, database)
    query_database(conn)
    conn.close()

PostgreSQL示例(使用psycopg2库):

import psycopg2

def create_conn(host, user, password, database):
    connection = psycopg2.connect(
        host=host,
        user=user,
        password=password,
        dbname=database
    )
    return connection

def query_database(connection):
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM your_table_name")

    rows = cursor.fetchall()
    for row in rows:
        print(row)

    cursor.close()

if __name__ == "__main__":
    host = "localhost"
    user = "your_username"
    password = "your_password"
    database = "your_database"

    conn = create_conn(host, user, password, database)
    query_database(conn)
    conn.close()

SQLite示例(使用sqlite3库):

import psycopg2

def create_conn(host, user, password, database):
    connection = psycopg2.connect(
        host=host,
        user=user,
        password=password,
        dbname=database
    )
    return connection

def query_database(connection):
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM your_table_name")

    rows = cursor.fetchall()
    for row in rows:
        print(row)

    cursor.close()

if __name__ == "__main__":
    host = "localhost"
    user = "your_username"
    password = "your_password"
    database = "your_database"

    conn = create_conn(host, user, password, database)
    query_database(conn)
    conn.close()

请将上述示例代码中的your_table_name替换为您要查询的实际表名,这些示例代码将连接到数据库、查询表中的所有数据并将结果打印到控制台。

图片[1]-怎么查数据库名称(用Python如何查询已经创建的数据库?)-不念博客

注意:在使用这些示例之前,请确保已安装所需的库(例如mysql-connector-pythonpsycopg2)以及适用于您的数据库管理系统的相关驱动程序。

© 版权声明
THE END