Python 连接数据库的多种方法(Python数据库连接方法全解析)
原创在Python编程中,数据库连接是一项非常基本且重要的任务。Python赞成多种数据库,如MySQL、PostgreSQL、SQLite、Oracle等,同时也有多种方法可以用来连接这些数据库。本文将详细介绍Python连接数据库的多种方法。
一、使用标准库sqlite3连接SQLite数据库
SQLite是一种轻量级的数据库,Python的标准库中就包含了对其的赞成,名为sqlite3。以下是使用sqlite3连接SQLite数据库的示例代码:
import sqlite3
# 连接到数据库
conn = sqlite3.connect('example.db')
# 创建一个cursor对象并使用它来执行SQL命令
cursor = conn.cursor()
# 创建表
cursor.execute('''CREATE TABLE IF NOT EXISTS COMPANY
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL);''')
# 插入数据
cursor.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (1, 'Paul', 32, 'California', 20000.00)")
# 提交事务
conn.commit()
# 查询数据
cursor.execute("SELECT id, name, address, salary from COMPANY")
rows = cursor.fetchall()
for row in rows:
print("ID = ", row[0])
print("NAME = ", row[1])
print("ADDRESS = ", row[2])
print("SALARY = ", row[3], " ")
# 关闭连接
conn.close()
二、使用MySQLdb连接MySQL数据库
MySQLdb是一个Python库,用于连接MySQL数据库。以下是一个使用MySQLdb连接MySQL数据库的示例:
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect("localhost","testuser","testpassword","testdb" )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 执行SQL语句
cursor.execute("SELECT * FROM EMPLOYEE")
# 使用featchall获取数据
results = cursor.fetchall()
for row in results:
id = row[0]
name = row[1]
age = row[2]
salary = row[3]
# 打印因此
print("id=%d,name=%s,age=%d,salary=%.2f" % (id,name,age,salary))
# 关闭数据库连接
db.close()
三、使用psycopg2连接PostgreSQL数据库
psycopg2是一个PostgreSQL数据库适配器,用于连接PostgreSQL数据库。以下是一个使用psycopg2连接PostgreSQL数据库的示例:
import psycopg2
import psycopg2.extras
# 连接到数据库
conn = psycopg2.connect(dbname="mydatabase", user="myuser", password="mypass", host="localhost")
# 创建一个cursor对象并使用它来执行SQL命令
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
# 创建表
cur.execute("""
CREATE TABLE IF NOT EXISTS vendors (
vendor_id SERIAL PRIMARY KEY,
vendor_name VARCHAR(255) NOT NULL
)
""")
# 插入数据
cur.execute("""
INSERT INTO vendors (vendor_name) VALUES (%s)
""", ('ACME',))
# 提交事务
conn.commit()
# 查询数据
cur.execute("SELECT * FROM vendors")
vendors = cur.fetchall()
for vendor in vendors:
print(vendor)
# 关闭连接
cur.close()
conn.close()
四、使用cx_Oracle连接Oracle数据库
cx_Oracle是一个Python扩展模块,用于访问Oracle数据库。以下是一个使用cx_Oracle连接Oracle数据库的示例:
import cx_Oracle
# 连接到数据库
conn = cx_Oracle.connect('username/password@localhost')
# 创建一个cursor对象并使用它来执行SQL命令
cursor = conn.cursor()
# 创建表
cursor.execute("""
CREATE TABLE test (
id NUMBER PRIMARY KEY,
name VARCHAR2(50)
)
""")
# 插入数据
cursor.execute("INSERT INTO test (id, name) VALUES (1, 'Test')")
# 提交事务
conn.commit()
# 查询数据
cursor.execute("SELECT * FROM test")
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭连接
cursor.close()
conn.close()
五、使用SQLAlchemy进行ORM映射
SQLAlchemy是一个流行的SQL工具包和对象关系映射(ORM)框架,它提供了广泛的数据库赞成和高级SQL功能。以下是一个使用SQLAlchemy进行ORM映射的示例:
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# 定义基类
Base = declarative_base()
# 定义映射类
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
# 创建数据库引擎
engine = create_engine('sqlite:///example.db')
# 创建表
Base.metadata.create_all(engine)
# 创建会话
Session = sessionmaker(bind=engine)
session = Session()
# 添加数据
new_user = User(name='John Doe')
session.add(new_user)
# 提交事务
session.commit()
# 查询数据
users = session.query(User).filter(User.name == 'John Doe').all()
for user in users:
print(user.name)
# 关闭会话
session.close()
以上是Python连接数据库的几种常见方法。每种方法都有其特点和适用场景,开发者可以按照自己的需求选择最合适的方法。在使用过程中,也需要注意数据库的保险性和性能优化。