在Ubuntu上,Python可以通过多种方式连接到数据库。以下是一些常见的数据库和相应的连接方法:
-
SQLite: SQLite是一个轻量级的数据库,它不需要一个单独的服务器进程,而是直接将数据存储在一个文件中。Python通过内置的
sqlite3
模块来支持SQLite。import sqlite3 # 连接到SQLite数据库(如果不存在,则会自动创建) conn = sqlite3.connect('example.db') # 创建一个Cursor对象使用cursor()方法 cursor = conn.cursor() # 执行SQL查询 cursor.execute('''CREATE TABLE IF NOT EXISTS stocks (date text, trans text, symbol text, qty real, price real)''') # 提交事务 conn.commit() # 关闭Cursor和连接 cursor.close() conn.close()
-
MySQL: 要连接到MySQL数据库,你需要安装
mysql-connector-python
或PyMySQL
。使用
pip
安装mysql-connector-python
:pip install mysql-connector-python
然后,你可以使用以下代码连接到MySQL数据库:
import mysql.connector # 连接到MySQL数据库 cnx = mysql.connector.connect(user='username', password='password', host='127.0.0.1', database='mydatabase') # 创建一个Cursor对象 cursor = cnx.cursor() # 执行SQL查询 cursor.execute("SELECT * FROM mytable") # 获取查询结果 for row in cursor: print(row) # 关闭Cursor和连接 cursor.close() cnx.close()
-
PostgreSQL: 对于PostgreSQL,你可以使用
psycopg2
库。使用
pip
安装psycopg2
:pip install psycopg2-binary
连接到PostgreSQL数据库的示例代码:
import psycopg2 # 连接到PostgreSQL数据库 conn = psycopg2.connect(dbname="mydatabase", user="username", password="password", host="127.0.0.1") # 创建一个Cursor对象 cursor = conn.cursor() # 执行SQL查询 cursor.execute("SELECT version()") # 获取查询结果 db_version = cursor.fetchone() print(db_version) # 关闭Cursor和连接 cursor.close() conn.close()
-
MongoDB: 对于NoSQL数据库如MongoDB,你可以使用
pymongo
库。使用
pip
安装pymongo
:pip install pymongo
连接到MongoDB数据库的示例代码:
from pymongo import MongoClient # 创建MongoClient实例 client = MongoClient('mongodb://localhost:27017/') # 获取数据库实例 db = client['mydatabase'] # 获取集合实例 collection = db['mycollection'] # 插入文档 post = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"], "date": datetime.datetime.utcnow()} post_id = collection.insert_one(post).inserted_id # 查询文档 for post in collection.find(): print(post)
在连接数据库时,请确保你的数据库服务正在运行,并且你已经正确配置了数据库的访问权限和网络设置。此外,对于生产环境,建议使用环境变量或其他安全的方式来管理数据库的用户名、密码等敏感信息。