在python中,数据库操作是通过数据库连接库(也称为数据库适配器或驱动程序)来完成的。这些库允许python代码与数据库进行交互,执行SQL查询,以及管理数据库中的数据。Python支持多种数据库,包括但不限于MySQL、PostgreSQL、SQLite、Oracle和MongoDB(尽管MongoDB是一个NoSQL数据库,但Python也有相应的库来操作它)。
下面是一些常用的python数据库操作库及其基本用法:
1. SQLite
SQLite是一个轻量级的数据库,它不需要一个独立的服务器进程或操作。python标准库中的sqlite3
模块提供了对SQLite数据库的支持。
示例代码:
import sqlite3
# 连接到SQLite数据库
# 如果文件不存在,会自动在当前目录创建:
conn = sqlite3.connect('example.db')
# 创建一个Cursor:
cursor = conn.cursor()
# 执行一条SQL语句,创建user表:
cursor.execute('CREATE TABLE IF NOT EXISTS user (id VARCHAR(20) PRIMARY KEY, name VARCHAR(20))')
# 继续执行一条SQL语句,插入一条记录:
cursor.execute('INSERT INTO user (id, name) VALUES (\'1\', \'Michael\')')
# 通过rowcount获得插入的行数:
print(cursor.rowcount)
# 关闭Cursor:
cursor.close()
# 提交事务:
conn.commit()
# 关闭Connection:
conn.close()
2. MySQL
对于MySQL数据库,你可以使用mysql-connector-python
或PyMySQL
等库。
使用mysql-connector-python
的示例:
首先,你需要安装mysql-connector-python
:
pip install mysql-connector-python
示例代码:
import mysql.connector
# 连接到MySQL数据库
conn = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
cursor = conn.cursor()
# 创建表
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255))")
# 插入数据
cursor.execute("INSERT INTO users (name) VALUES (%s)", ("John",))
# 提交事务
conn.commit()
# 查询数据
cursor.execute("SELECT * FROM users")
for row in cursor:
print(row)
# 关闭Cursor和Connection
cursor.close()
conn.close()
3. PostgreSQL
对于PostgreSQL,你可以使用psycopg2
库。
使用psycopg2
的示例:
首先,安装psycopg2
:
示例代码:
pip install psycopg2-binary
import psycopg2
# 连接到PostgreSQL数据库
conn = psycopg2.connect(
dbname="yourdbname",
user="yourusername",
password="yourpassword",
host="127.0.0.1",
port="5432"
)
cursor = conn.cursor()
# 创建表
cursor.execute("CREATE TABLE IF NOT EXISTS test (id SERIAL PRIMARY KEY, num INTEGER)")
# 插入数据
cursor.execute("INSERT INTO test (num) VALUES (%s)", (100,))
# 提交事务
conn.commit()
# 查询数据
cursor.execute("SELECT * FROM test")
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭Cursor和Connection
cursor.close()
conn.close()
4. MongoDB
MongoDB是一个NoSQL数据库,你可以使用pymongo
库来操作它。
使用pymongo
的示例:
首先,安装pymongo
:
pip install pymongo
示例代码:
from pymongo import MongoClient
# 连接到MongoDB
client = MongoClient('localhost', 27017)
# 选择数据库
db = client['mydatabase']
# 选择集合
collection = db['mycollection']
# 插入文档
post = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"]}
post_id = collection.insert_one(post).inserted_id
# 查询文档