在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
请根据你的实际情况替换示例中的数据库连接信息、表名等。