云网站建设017年青,网站建设与维护基础知识,东莞住建局局长主动投案,河北最近发生的重大新闻Python学习#xff1a;数据库操作篇
在这个信息爆炸的时代#xff0c;数据库就像是一个个巨大的宝藏库#xff0c;里面藏着无数珍贵的数据宝石。而Python#xff0c;就是那把能够打开这些宝藏库的神奇钥匙。在这一章中#xff0c;我们将一起学习如何使用Python来操作数据…Python学习数据库操作篇
在这个信息爆炸的时代数据库就像是一个个巨大的宝藏库里面藏着无数珍贵的数据宝石。而Python就是那把能够打开这些宝藏库的神奇钥匙。在这一章中我们将一起学习如何使用Python来操作数据库包括SQLite、ORM对象关系映射以及NoSQL数据库。
1. SQLite
SQLite是一个轻量级的数据库它不需要独立的服务器进程数据库文件就是它存储数据的地方。在Python中我们可以使用sqlite3模块来操作SQLite数据库。
创建SQLite数据库 在Python中你可以通过sqlite3模块连接到一个SQLite数据库如果数据库不存在它将自动创建。
import sqlite3def create_connection(db_file): 创建到SQLite数据库的连接 conn Nonetry:conn sqlite3.connect(db_file)return connexcept Exception as e:print(e)def create_table(conn): 创建表 try:c conn.cursor()c.execute(CREATE TABLE IF NOT EXISTS users (id integer PRIMARY KEY,name text NOT NULL,age integer);)except Exception as e:print(e)# 创建数据库连接
conn create_connection(mydatabase.db)
if conn is not None:create_table(conn)
else:print(无法创建数据库连接。)在这个例子中我们创建了一个名为mydatabase.db的SQLite数据库并在其中创建了一个名为users的表。
插入数据 你可以使用execute方法来插入数据。
def insert_user(conn, user): 新增用户 sql INSERT INTO users(name, age)VALUES(?,?) cur conn.cursor()cur.execute(sql, user)conn.commit()return cur.lastrowid# 插入数据
user (Kimi, 30)
id insert_user(conn, user)
print(f用户ID{id})在这个例子中我们向users表中插入了一个新的用户。
查询数据 你可以使用execute方法来查询数据。
def select_all_users(conn): 查询所有用户 cur conn.cursor()cur.execute(SELECT * FROM users)rows cur.fetchall()for row in rows:print(row)# 查询数据
select_all_users(conn)在这个例子中我们查询了users表中的所有用户。
更新和删除数据 你可以使用execute方法来更新和删除数据。
def update_user(conn, user): 更新用户 sql UPDATE usersSET name ?WHERE id ?cur conn.cursor()cur.execute(sql, user)conn.commit()def delete_user(conn, id): 删除用户 sql DELETE FROM users WHERE id?cur conn.cursor()cur.execute(sql, (id,))conn.commit()# 更新数据
update_user(conn, (Moonshot, 30))# 删除数据
delete_user(conn, 1)在这个例子中我们更新了一个用户的名字并删除了一个用户。
实例创建一个图书馆管理系统
def create_library_db():conn create_connection(library.db)if conn is not None:create_table(conn)return connelse:print(无法创建数据库连接。)return Nonedef add_book(conn, book): 添加书籍 sql INSERT INTO books(title, author, year)VALUES(?,?,?) cur conn.cursor()cur.execute(sql, book)conn.commit()return cur.lastrowiddef list_books(conn): 列出所有书籍 cur conn.cursor()cur.execute(SELECT * FROM books)rows cur.fetchall()for row in rows:print(row)# 创建数据库连接
conn create_library_db()
if conn is not None:# 添加书籍book (Python编程, Kimi, 2024)id add_book(conn, book)print(f书籍ID{id})# 列出书籍list_books(conn)
else:print(无法创建数据库连接。)在这个例子中我们创建了一个图书馆管理系统它允许我们添加书籍和列出所有书籍。
2. ORM对象关系映射
ORM是一种编程技术它允许你使用面向对象的方法来操作数据库。在Python中我们可以使用SQLAlchemy这样的ORM库来操作数据库。
安装SQLAlchemy 首先你需要安装SQLAlchemy。
pip install SQLAlchemy定义模型 你可以定义模型类来映射数据库表。
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmakerBase declarative_base()class User(Base):__tablename__ usersid Column(Integer, primary_keyTrue)name Column(String)age Column(Integer)# 创建数据库引擎
engine create_engine(sqlite:///mydatabase.db)# 创建表
Base.metadata.create_all(engine)在这个例子中我们定义了一个User模型并创建了一个SQLite数据库。
添加数据 你可以使用ORM会话来添加数据。
Session sessionmaker(bindengine)
session Session()new_user User(nameKimi, age30)
session.add(new_user)
session.commit()在这个例子中我们添加了一个新的用户。
查询数据 你可以使用ORM会话来查询数据。
# 查询所有用户
users session.query(User).all()
for user in users:print(user.name, user.age)在这个例子中我们查询了所有用户。
更新和删除数据 你可以使用ORM会话来更新和删除数据。
# 更新用户
user_to_update session.query(User).filter_by(nameKimi).first()
user_to_update.age 31
session.commit()# 删除用户
user_to_delete session.query(User).filter_by(nameKimi).first()
session.delete(user_to_delete)
session.commit()在这个例子中我们更新了一个用户的年龄并删除了一个用户。
实例创建一个博客系统
class Post(Base):__tablename__ postsid Column(Integer, primary_keyTrue)title Column(String)content Column(String)# 创建表
Base.metadata.create_all(engine)# 添加文章
new_post Post(titlePython学习大纲, content这是一篇关于Python学习大纲的文章。)
session.add(new_post)
session.commit()# 查询文章
posts session.query(Post).all()
for post in posts:print(post.title, post.content)# 更新文章
post_to_update session.query(Post).filter_by(titlePython学习大纲).first()
post_to_update.content 这是一篇更新后的关于Python学习大纲的文章。
session.commit()# 删除文章
post_to_delete session.query(Post).filter_by(titlePython学习大纲).first()
session.delete(post_to_delete)
session.commit()在这个例子中我们创建了一个博客系统它允许我们添加文章、查询文章、更新文章和删除文章。
3. NoSQL数据库
NoSQL数据库是一种非关系型数据库它不需要固定的表结构。在Python中我们可以使用PyMongo这样的库来操作MongoDB这样的NoSQL数据库。
安装PyMongo 首先你需要安装PyMongo。
pip install pymongo连接到MongoDB 你可以使用PyMongo连接到MongoDB。
from pymongo import MongoClientclient MongoClient(mongodb://localhost:27017/)
db client[mydatabase]在这个例子中我们连接到了一个名为mydatabase的MongoDB数据库。
插入数据 你可以使用PyMongo插入数据。
users_collection db[users]new_user {name: Kimi, age: 30}
users_collection.insert_one(new_user)在这个例子中我们向users集合中插入了一个新的用户。
查询数据 你可以使用PyMongo查询数据。
users users_collection.find()
for user in users:print(user[name], user[age])在这个例子中我们查询了users集合中的所有用户。
更新和删除数据 你可以使用PyMongo更新和删除数据。
# 更新用户
users_collection.update_one({name: Kimi}, {$set: {age: 31}})# 删除用户
users_collection.delete_one({name: Kimi})在这个例子中我们更新了一个用户的年龄并删除了一个用户。
实例创建一个购物车系统
products_collection db[products]
carts_collection db[carts]# 添加商品
new_product {name: Python编程书籍, price
: 100}
products_collection.insert_one(new_product)# 添加购物车
new_cart {user: Kimi, items: [{product: Python编程书籍, quantity: 2}]}
carts_collection.insert_one(new_cart)# 查询购物车
carts carts_collection.find()
for cart in carts:print(cart[user], cart[items])# 更新购物车
carts_collection.update_one({user: Kimi}, {$set: {items: [{product: Python编程书籍, quantity: 3}]}})在这个例子中我们创建了一个购物车系统它允许我们添加商品、添加购物车、查询购物车和更新购物车。
小结
数据库操作是Python中的一项强大技能它让我们的程序能够存储和查询大量的数据。通过SQLite我们可以操作关系型数据库。通过ORM我们可以以面向对象的方式操作数据库。通过NoSQL数据库我们可以操作非关系型数据库。
现在你已经掌握了Python中数据库操作的基础。但是这只是冰山一角。在编程的世界里还有更多高级的概念等着你去探索。编程就像是一场冒险而你已经迈出了第一步。祝你在编程的世界里旅途愉快