在Ubuntu上使用Python连接数据库,通常需要以下几个步骤:
-
安装数据库驱动:根据你使用的数据库类型,你需要安装相应的Python驱动。以下是一些常见数据库的驱动安装方法:
-
MySQL: 使用
pip安装mysql-connector-python包:pip install mysql-connector-python -
PostgreSQL: 使用
pip安装psycopg2包:pip install psycopg2或者安装
psycopg2-binary包(不需要编译环境):pip install psycopg2-binary -
SQLite: Python标准库中已经包含了SQLite3模块,无需额外安装。
-
MongoDB: 使用
pip安装pymongo包:pip install pymongo
-
-
编写Python代码:根据你使用的数据库和驱动,编写相应的Python代码来连接数据库。以下是一些示例:
-
MySQL:
import mysql.connector cnx = mysql.connector.connect(user='username', password='password', host='localhost', database='your_database') cursor = cnx.cursor() query = ("SELECT * FROM your_table") cursor.execute(query) for row in cursor: print(row) cursor.close() cnx.close() -
PostgreSQL:
import psycopg2 conn = psycopg2.connect(dbname='your_database', user='username', password='password', host='localhost') cursor = conn.cursor() cursor.execute("SELECT * FROM your_table") rows = cursor.fetchall() for row in rows: print(row) cursor.close() conn.close() -
SQLite:
import sqlite3 conn = sqlite3.connect('your_database.db') cursor = conn.cursor() cursor.execute("SELECT * FROM your_table") rows = cursor.fetchall() for row in rows: print(row) cursor.close() conn.close() -
MongoDB:
from pymongo import MongoClient client = MongoClient('mongodb://username:password@localhost:27017/your_database') db = client['your_database'] collection = db['your_table'] documents = collection.find() for doc in documents: print(doc)
-
-
运行Python代码:在终端中运行你的Python脚本,例如:
python your_script.py
请根据你的实际情况替换示例中的数据库连接信息、表名等。
以上就是关于“Ubuntu Python数据库连接怎么弄”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm