在Ubuntu上使用Python连接数据库,通常需要安装相应的数据库驱动和客户端库。以下是一些常见数据库的连接方法:
sudo apt update
sudo apt install python3-mysqldb
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()
sudo apt update
sudo apt install python3-psycopg2
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()
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()
sudo apt update
sudo apt install python3-pymongo
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连接的示例。根据你使用的数据库类型,选择相应的客户端库并进行安装,然后按照示例代码进行连接和操作即可。