Python中常用的数据库模块(module)介绍及使用方法
发布时间:2023-12-24 22:03:36
Python中常用的数据库模块有以下几个:
1. SQLite3: SQLite3是一个轻量级的嵌入式数据库,适合在小型项目中使用。它在Python的标准库中,无需额外安装。以下是一个使用SQLite3模块的例子:
import sqlite3
# 连接数据库
conn = sqlite3.connect('example.db')
# 创建一个游标
cursor = conn.cursor()
# 创建表
cursor.execute('''
CREATE TABLE stocks
(date text, trans text, symbol text, qty real, price real)
''')
# 插入数据
cursor.execute("INSERT INTO stocks VALUES ('2006-01-05', 'BUY', 'RHAT', 100, 35.14)")
# 保存更改
conn.commit()
# 查询数据
cursor.execute('SELECT * FROM stocks')
print(cursor.fetchall())
# 关闭连接
conn.close()
2. MySQL Connector/Python: MySQL Connector/Python是一个用于连接MySQL数据库的模块,需要通过pip安装。以下是一个使用MySQL Connector/Python模块的例子:
import mysql.connector
# 连接数据库
conn = mysql.connector.connect(
user='username',
password='password',
host='localhost',
database='database_name'
)
# 创建一个游标
cursor = conn.cursor()
# 创建表
cursor.execute('''
CREATE TABLE stocks
(date text, trans text, symbol text, qty real, price real)
''')
# 插入数据
cursor.execute("INSERT INTO stocks VALUES ('2006-01-05', 'BUY', 'RHAT', 100, 35.14)")
# 保存更改
conn.commit()
# 查询数据
cursor.execute('SELECT * FROM stocks')
print(cursor.fetchall())
# 关闭连接
conn.close()
3. psycopg2: psycopg2是一个用于连接PostgreSQL数据库的模块,同样需要通过pip安装。以下是一个使用psycopg2模块的例子:
import psycopg2
# 连接数据库
conn = psycopg2.connect(
dbname='database_name',
user='username',
password='password',
host='localhost'
)
# 创建一个游标
cursor = conn.cursor()
# 创建表
cursor.execute('''
CREATE TABLE stocks
(date text, trans text, symbol text, qty real, price real)
''')
# 插入数据
cursor.execute("INSERT INTO stocks VALUES ('2006-01-05', 'BUY', 'RHAT', 100, 35.14)")
# 保存更改
conn.commit()
# 查询数据
cursor.execute('SELECT * FROM stocks')
print(cursor.fetchall())
# 关闭连接
conn.close()
以上是对常用的数据库模块的简介和使用方法。根据具体的项目需求和数据库类型,可以选择合适的模块进行连接和操作数据库。
