当前位置:首页 > 数据库 > 正文

python怎么查询数据库

Python的 sqlite3、 pymysql或 sqlalchemy等库

Python中查询数据库是一项常见的任务,通常用于数据存储、检索和处理,Python提供了多种库来与不同类型的数据库进行交互,如SQLite、MySQL、PostgreSQL等,以下是详细的步骤和示例代码,展示如何使用Python查询数据库。

选择数据库和安装相应的库

你需要选择一个数据库并安装相应的Python库,以下是一些常见的数据库及其对应的Python库:

python怎么查询数据库 第1张

  • SQLite: 内置于Python标准库中,无需额外安装。
  • MySQL: 使用mysql-connector-python或PyMySQL库。
  • PostgreSQL: 使用psycopg2库。

安装库

pip install mysql-connector-python psycopg2

连接到数据库

连接到数据库是查询的第一步,以下是如何连接到不同类型的数据库的示例。

SQLite

import sqlite3 # 连接到SQLite数据库(如果数据库不存在,则会自动创建) conn = sqlite3.connect('example.db') cursor = conn.cursor()

MySQL

import mysql.connector # 连接到MySQL数据库 conn = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="yourdatabase" ) cursor = conn.cursor()

PostgreSQL

import psycopg2 # 连接到PostgreSQL数据库 conn = psycopg2.connect( host="localhost", database="yourdatabase", user="yourusername", password="yourpassword" ) cursor = conn.cursor()

创建表和插入数据

在查询之前,通常需要有一个表来存储数据,以下是如何创建表和插入数据的示例。

SQLite

# 创建表 cursor.execute(''' CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, age INTEGER ) ''') # 插入数据 cursor.execute('INSERT INTO users (name, age) VALUES (?, ?)', ('Alice', 25)) cursor.execute('INSERT INTO users (name, age) VALUES (?, ?)', ('Bob', 30)) conn.commit()

MySQL

# 创建表 cursor.execute(''' CREATE TABLE IF NOT EXISTS users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, age INT ) ''') # 插入数据 cursor.execute('INSERT INTO users (name, age) VALUES (%s, %s)', ('Alice', 25)) cursor.execute('INSERT INTO users (name, age) VALUES (%s, %s)', ('Bob', 30)) conn.commit()

PostgreSQL

# 创建表 cursor.execute(''' CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL, age INT ) ''') # 插入数据 cursor.execute('INSERT INTO users (name, age) VALUES (%s, %s)', ('Alice', 25)) cursor.execute('INSERT INTO users (name, age) VALUES (%s, %s)', ('Bob', 30)) conn.commit()

查询数据

查询数据是数据库操作的核心,以下是如何执行查询并获取结果的示例。

python怎么查询数据库 第2张

SQLite

# 查询所有用户 cursor.execute('SELECT FROM users') rows = cursor.fetchall() for row in rows: print(row)

MySQL

# 查询所有用户 cursor.execute('SELECT FROM users') rows = cursor.fetchall() for row in rows: print(row)

PostgreSQL

# 查询所有用户 cursor.execute('SELECT FROM users') rows = cursor.fetchall() for row in rows: print(row)

关闭连接

在完成数据库操作后,务必关闭连接以释放资源。

cursor.close() conn.close()

使用ORM(对象关系映射)

除了直接使用SQL查询,Python还提供了ORM(对象关系映射)工具,如SQLAlchemy,它可以帮助你以更面向对象的方式操作数据库。

安装SQLAlchemy

pip install sqlalchemy

使用SQLAlchemy查询数据

from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker # 创建引擎 engine = create_engine('sqlite:///example.db') Base = declarative_base() # 定义模型 class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) age = Column(Integer) # 创建会话 Session = sessionmaker(bind=engine) session = Session() # 查询所有用户 users = session.query(User).all() for user in users: print(user.id, user.name, user.age) # 关闭会话 session.close()

常见问题及解决方案

Q1: 如何防止SQL载入?

A1: 使用参数化查询或ORM工具可以有效防止SQL载入,在SQLite中使用作为占位符,在MySQL中使用%s作为占位符。

Q2: 如何处理数据库连接错误?

A2: 可以使用try-except块捕获异常,并在发生错误时进行适当的处理。

try: conn = mysql.connector.connect(host="localhost", user="yourusername", password="yourpassword", database="yourdatabase") except mysql.connector.Error as err: print(f"Error: {err}")

Python提供了多种方式来查询数据库,无论是直接使用SQL还是通过ORM工具,都可以方便地进行数据库操作。

python怎么查询数据库 第3张

0