首页主机资讯Linux环境下Python如何连接数据库

Linux环境下Python如何连接数据库

时间2025-10-01 16:34:04发布访客分类主机资讯浏览1047
导读:在Linux环境下,Python可以通过多种方式连接到数据库。以下是一些常见的数据库和相应的Python库: MySQL: 使用mysql-connector-python或PyMySQL库。 安装:pip install mysql-...

在Linux环境下,Python可以通过多种方式连接到数据库。以下是一些常见的数据库和相应的Python库:

  1. MySQL: 使用mysql-connector-pythonPyMySQL库。 安装:pip install mysql-connector-pythonpip install pymysql 示例代码(使用mysql-connector-python):

    import mysql.connector
    
    connection = mysql.connector.connect(
        host="localhost",
        user="your_username",
        password="your_password",
        database="your_database"
    )
    
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM your_table")
    result = cursor.fetchall()
    
    for row in result:
        print(row)
    
    cursor.close()
    connection.close()
    
  2. PostgreSQL: 使用psycopg2库。 安装:pip install psycopg2pip install psycopg2-binary 示例代码:

    import psycopg2
    
    connection = psycopg2.connect(
        dbname="your_database",
        user="your_username",
        password="your_password",
        host="localhost"
    )
    
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM your_table")
    result = cursor.fetchall()
    
    for row in result:
        print(row)
    
    cursor.close()
    connection.close()
    
  3. SQLite: 使用内置的sqlite3库。 示例代码:

    import sqlite3
    
    connection = sqlite3.connect("your_database.db")
    
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM your_table")
    result = cursor.fetchall()
    
    for row in result:
        print(row)
    
    cursor.close()
    connection.close()
    
  4. MongoDB: 使用pymongo库。 安装:pip install pymongo 示例代码:

    from pymongo import MongoClient
    
    client = MongoClient("mongodb://your_username:your_password@localhost:27017/your_database")
    
    db = client.your_database
    collection = db.your_table
    
    for document in collection.find():
        print(document)
    

请根据您使用的数据库类型选择合适的库,并确保已正确安装。在运行示例代码之前,请替换为您自己的数据库连接信息。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: Linux环境下Python如何连接数据库
本文地址: https://pptw.com/jishu/715958.html
Linux中Python脚本执行权限怎么设置 PHP-FPM在Linux下的高并发处理

游客 回复需填写必要信息