在Linux环境下,Python可以通过多种方式连接到数据库。以下是一些常见的数据库和相应的Python库:
-
MySQL: 使用
mysql-connector-python或PyMySQL库。 安装:pip install mysql-connector-python或pip 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() -
PostgreSQL: 使用
psycopg2库。 安装:pip install psycopg2或pip 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() -
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() -
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)
请根据您使用的数据库类型选择合适的库,并确保已正确安装。在运行示例代码之前,请替换为您自己的数据库连接信息。
以上就是关于“Linux环境下Python如何连接数据库”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm