温馨提示×

Python中的SQL查询如何实现约束和默认值设置

sql
小樊
84
2024-08-18 13:59:38
栏目: 云计算

在Python中执行SQL查询时,可以通过SQL语句或者使用ORM框架(如SQLAlchemy)来实现约束和默认值设置。

  1. 使用SQL语句:在执行SQL查询时,可以直接使用SQL语句来设置约束和默认值。例如,在创建表时可以使用CREATE TABLE语句来设置约束和默认值,如下所示:
import sqlite3

# 连接到SQLite数据库
conn = sqlite3.connect('example.db')
cursor = conn.cursor()

# 创建表并设置约束和默认值
sql_query = '''
CREATE TABLE users (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    age INTEGER DEFAULT 18
);
'''
cursor.execute(sql_query)

# 关闭数据库连接
conn.close()
  1. 使用ORM框架:如果使用ORM框架(如SQLAlchemy),可以在定义模型类时设置约束和默认值。例如,可以使用SQLAlchemy来定义一个用户模型类,并设置约束和默认值,如下所示:
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)
    age = Column(Integer, default=18)

# 创建数据库引擎并创建表
engine = create_engine('sqlite:///example.db')
Base.metadata.create_all(engine)

通过上述两种方法,可以在Python中执行SQL查询时实现约束和默认值设置。

0