在Ubuntu上使用Python连接数据库,通常需要安装相应的数据库驱动和客户端库。以下是一些常见数据库的连接方法:
1. 连接MySQL数据库
安装MySQL客户端库
sudo apt update sudo apt install python3-mysqldb
使用Python连接MySQL
import MySQLdb # 连接数据库 conn = MySQLdb.connect( host="localhost", user="your_username", passwd="your_password", db="your_database" ) # 创建游标 cursor = conn.cursor() # 执行SQL查询 cursor.execute("SELECT * FROM your_table") # 获取查询结果 results = cursor.fetchall() for row in results: print(row) # 关闭游标和连接 cursor.close() conn.close()
2. 连接PostgreSQL数据库
安装PostgreSQL客户端库
sudo apt update sudo apt install python3-psycopg2
使用Python连接PostgreSQL
import psycopg2 # 连接数据库 conn = psycopg2.connect( dbname="your_database", user="your_username", password="your_password", host="localhost", port="5432" ) # 创建游标 cursor = conn.cursor() # 执行SQL查询 cursor.execute("SELECT * FROM your_table") # 获取查询结果 results = cursor.fetchall() for row in results: print(row) # 关闭游标和连接 cursor.close() conn.close()
3. 连接SQLite数据库
使用Python内置的sqlite3模块
import sqlite3 # 连接数据库 conn = sqlite3.connect('your_database.db') # 创建游标 cursor = conn.cursor() # 执行SQL查询 cursor.execute("SELECT * FROM your_table") # 获取查询结果 results = cursor.fetchall() for row in results: print(row) # 关闭游标和连接 cursor.close() conn.close()
4. 连接MongoDB数据库
安装MongoDB客户端库
sudo apt update sudo apt install python3-pymongo
使用Python连接MongoDB
from pymongo import MongoClient # 连接数据库 client = MongoClient('mongodb://localhost:27017/') # 选择数据库 db = client['your_database'] # 选择集合 collection = db['your_collection'] # 查询文档 documents = collection.find() for document in documents: print(document) # 关闭连接 client.close()
总结
以上是几种常见数据库在Ubuntu上使用Python连接的示例。根据你使用的数据库类型,选择相应的客户端库并进行安装,然后按照示例代码进行连接和操作即可。