Python连接数据库方法介绍
python可以通过多种方式与数据库连接,常用的库包括 sqlite3、MySQLdb、psycopg2 和 SQLAlchemy 等。以下是 Python 连接数据库的基本步骤:
- 安装数据库驱动
根据数据库类型,安装相应的 Python 库:
SQLite: 内置支持,无需额外安装。
MySQL: 安装 mysql-connector-python 或 pymysql。
PostgreSQL: 安装 psycopg2。
SQLAlchemy: 支持多种数据库,安装 SQLAlchemy。
bash
复制
pip install mysql-connector-python pymysql psycopg2 sqlalchemy
2. 连接数据库
使用相应的库连接数据库。
SQLite 示例
python
复制
import sqlite3
连接数据库(若不存在则创建)
conn = sqlite3.connect(‘example.db’)
创建游标
cursor = conn.cursor()
执行SQL语句
cursor.execute(‘’’CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)’’’)
插入数据
cursor.execute(“INSERT INTO users (name, age) VALUES (‘Alice’, 30)”)
提交事务
conn.commit()
查询数据
cursor.execute(“SELECT * FROM users”)
rows = cursor.fetchall()
for row in rows:
print(row)
关闭连接
conn.close()
MySQL 示例
python
复制
import mysql.connector
连接数据库
conn = mysql.connector.connect(
host=”localhost”,
user=”root”,
password=”password”,
database=”testdb”
)
创建游标
cursor = conn.cursor()
执行SQL语句
cursor.execute(‘’’CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT)’’’)
插入数据
cursor.execute(“INSERT INTO users (name, age) VALUES (‘Alice’, 30)”)
提交事务
conn.commit()
查询数据
cursor.execute(“SELECT * FROM users”)
rows = cursor.fetchall()
for row in rows:
print(row)
关闭连接
conn.close()
PostgreSQL 示例
python
复制
import psycopg2
连接数据库
conn = psycopg2.connect(
host=”localhost”,
dbname=”testdb”,
user=”postgres”,
password=”password”
)
创建游标
cursor = conn.cursor()
执行SQL语句
cursor.execute(‘’’CREATE TABLE IF NOT EXISTS users (id SERIAL PRIMARY KEY, name VARCHAR(255), age INT)’’’)
插入数据
cursor.execute(“INSERT INTO users (name, age) VALUES (‘Alice’, 30)”)
提交事务
conn.commit()
查询数据
cursor.execute(“SELECT * FROM users”)
rows = cursor.fetchall()
for row in rows:
print(row)
关闭连接
conn.close()
3. 使用 ORM(如 SQLAlchemy)
ORM(对象关系映射)允许通过 Python 对象操作数据库。
python
复制
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’, echo=True)
声明基类
Base = declarative_base()
定义模型
class User(Base):
tablename = ‘users’
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
创建表
Base.metadata.create_all(engine)
创建会话
Session = sessionmaker(bind=engine)
session = Session()
插入数据
new_user = User(name=’Alice’, age=30)
session.add(new_user)
session.commit()
查询数据
users = session.query(User).all()
for user in users:
print(user.id, user.name, user.age)
本文由 海星量化研究所 作者提供,转载请保留链接和署名!网址:https://qmt.hxquant.com/?id=27
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源; 2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任; 3.作者投稿可能会经我们编辑修改或补充。