在Ubuntu上使用Python连接数据库,通常需要安装相应的数据库驱动和库。以下是一些常见数据库的连接方法:
sudo apt update
sudo apt install python3-mysqldb
import MySQLdb
# 连接到数据库
db = MySQLdb.connect(host="localhost", user="your_username", passwd="your_password", db="your_database")
# 创建游标对象
cursor = db.cursor()
# 执行SQL查询
cursor.execute("SELECT VERSION()")
# 获取单条数据
data = cursor.fetchone()
print("Database version : %s " % data)
# 关闭数据库连接
db.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"
)
# 创建游标对象
cur = conn.cursor()
# 执行SQL查询
cur.execute("SELECT version();")
# 获取单条数据
db_version = cur.fetchone()
print("PostgreSQL database version:", db_version)
# 关闭游标和连接
cur.close()
conn.close()
SQLite是一个嵌入式数据库,不需要额外的服务器进程。
import sqlite3
# 连接到SQLite数据库(如果不存在则会自动创建)
conn = sqlite3.connect('example.db')
# 创建游标对象
cursor = conn.cursor()
# 创建表
cursor.execute('''CREATE TABLE IF NOT EXISTS stocks
(date text, trans text, symbol text, qty real, price real)''')
# 插入数据
cursor.execute("INSERT INTO stocks VALUES ('2023-04-01','BUY','RHAT',100,35.14)")
# 提交事务
conn.commit()
# 查询数据
cursor.execute("SELECT * FROM stocks")
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭游标和连接
cursor.close()
conn.close()
MongoDB是一个NoSQL数据库,使用pymongo库进行连接。
pip3 install pymongo
from pymongo import MongoClient
# 连接到MongoDB服务器
client = MongoClient('mongodb://localhost:27017/')
# 选择数据库
db = client['your_database']
# 选择集合
collection = db['your_collection']
# 插入文档
document = {"name": "Alice", "age": 25}
collection.insert_one(document)
# 查询文档
for doc in collection.find():
print(doc)
根据你使用的数据库类型,选择相应的Python库进行安装和连接。常见的数据库包括MySQL、PostgreSQL、SQLite和MongoDB。每种数据库都有其特定的连接方式和操作方法,但基本的连接流程是相似的:安装库、建立连接、执行SQL查询或操作、关闭连接。