Python函数操作数据库的方法
Python中操作数据库的方法有多种,常用的有使用内置库sqlite3操作SQLite数据库和使用第三方库pymysql操作MySQL数据库。下面将具体介绍这两种方法。
1. 使用sqlite3操作SQLite数据库:
SQLite是一个轻量级的嵌入式数据库,无需独立的服务器进程或配置文件即可访问。在Python中,可以使用内置的sqlite3模块来操作SQLite数据库。
首先,导入sqlite3模块:import sqlite3
然后,连接到数据库:conn = sqlite3.connect('database.db')
创建游标对象:cursor = conn.cursor()
创建表格:cursor.execute("CREATE TABLE IF NOT EXISTS students (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)")
插入数据:cursor.execute("INSERT INTO students (id, name, age) VALUES (1, 'Tom', 18)")
查询数据:cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
for row in rows:
print(row)
提交修改:conn.commit()
关闭数据库连接:conn.close()
2. 使用pymysql操作MySQL数据库:
MySQL是一种广泛使用的开源关系型数据库管理系统,Python中可以使用pymysql模块来操作MySQL数据库。
首先,导入pymysql模块:import pymysql
然后,连接到数据库:conn = pymysql.connect(host='localhost', user='root', password='password', db='database')
创建游标对象:cursor = conn.cursor()
创建表格:cursor.execute("CREATE TABLE IF NOT EXISTS students (id INT PRIMARY KEY, name VARCHAR(20), age INT)")
插入数据:cursor.execute("INSERT INTO students (id, name, age) VALUES (1, 'Tom', 18)")
查询数据:cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
for row in rows:
print(row)
提交修改:conn.commit()
关闭数据库连接:conn.close()
以上是使用sqlite3和pymysql两种方法操作数据库的基本流程。根据实际需求,还可以进行更复杂的操作,如更新数据、删除数据等。此外,还有其他的库如psycopg2用于操作PostgreSQL、cx_Oracle用于操作Oracle等。通过使用这些库,可以轻松地在Python中操作数据库。
