在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 VERSION()")
# 获取单条数据
data = cursor.fetchone()
print("Database version : %s " % data)
# 关闭连接
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 version();")
# 获取单条数据
db_version = cursor.fetchone()
print("Database version : %s " % db_version)
# 关闭连接
conn.close()
SQLite是一个嵌入式数据库,不需要额外的客户端库。
import sqlite3
# 连接数据库
conn = sqlite3.connect('your_database.db')
# 创建游标
cursor = conn.cursor()
# 执行SQL查询
cursor.execute("SELECT sqlite_version();")
# 获取单条数据
sqlite_version = cursor.fetchone()
print("SQLite version : %s " % sqlite_version)
# 关闭连接
conn.close()
sudo apt update
sudo apt install python3-pymongo
from pymongo import MongoClient
# 连接MongoDB
client = MongoClient('mongodb://localhost:27017/')
# 选择数据库
db = client['your_database']
# 选择集合
collection = db['your_collection']
# 插入文档
document = {"name": "John", "age": 30}
collection.insert_one(document)
# 查询文档
for doc in collection.find():
print(doc)
python3-mysqldbpython3-psycopg2python3-pymongo根据你的需求选择合适的数据库和相应的Python库进行连接和操作。