Python与数据库:MySQL、SQLite实战教程

在当今数据驱动的世界中,掌握数据库操作是每个开发者必备的技能。Python作为一种简洁且强大的编程语言,与数据库的结合更是如虎添翼。本文将带你深入探索Python与两种常用数据库——MySQL和SQLite的实战应用。

Python与数据库:MySQL、SQLite实战教程

一、MySQL与Python的邂逅

1.1 安装与配置

首先,确保你已经安装了MySQL数据库和Python环境。接下来,安装mysql-connector-python库,以便Python能够与MySQL进行通信。

pip install mysql-connector-python

1.2 连接数据库

使用以下代码建立与MySQL数据库的连接:

import mysql.connector

conn = mysql.connector.connect(
    host='localhost',
    user='your_username',
    password='your_password',
    database='your_database'
)

cursor = conn.cursor()

1.3 执行SQL语句

创建一个简单的表并插入数据:

cursor.execute('CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT)')
cursor.execute('INSERT INTO users (name, age) VALUES (%s, %s)', ('Alice', 28))
conn.commit()

1.4 查询数据

查询并打印表中的数据:

cursor.execute('SELECT * FROM users')
for row in cursor.fetchall():
    print(row)

二、SQLite的轻量级魅力

2.1 安装与配置

SQLite是一个轻量级的数据库,Python内置了对SQLite的支持,无需额外安装。

2.2 连接数据库

使用sqlite3模块连接数据库:

import sqlite3

conn = sqlite3.connect('example.db')
cursor = conn.cursor()

2.3 创建表与插入数据

创建表并插入数据:

cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)')
cursor.execute('INSERT INTO users (name, age) VALUES (?, ?)', ('Bob', 25))
conn.commit()

2.4 查询数据

查询并打印表中的数据:

cursor.execute('SELECT * FROM users')
for row in cursor.fetchall():
    print(row)

三、实战案例:用户管理系统

3.1 需求分析

我们将创建一个简单的用户管理系统,支持添加、查询和删除用户。

3.2 MySQL实现

def add_user(name, age):
    cursor.execute('INSERT INTO users (name, age) VALUES (%s, %s)', (name, age))
    conn.commit()

def get_users():
    cursor.execute('SELECT * FROM users')
    return cursor.fetchall()

def delete_user(user_id):
    cursor.execute('DELETE FROM users WHERE id = %s', (user_id,))
    conn.commit()

# 示例操作
add_user('Charlie', 30)
print(get_users())
delete_user(1)
print(get_users())

3.3 SQLite实现

def add_user(name, age):
    cursor.execute('INSERT INTO users (name, age) VALUES (?, ?)', (name, age))
    conn.commit()

def get_users():
    cursor.execute('SELECT * FROM users')
    return cursor.fetchall()

def delete_user(user_id):
    cursor.execute('DELETE FROM users WHERE id = ?', (user_id,))
    conn.commit()

# 示例操作
add_user('Dave', 35)
print(get_users())
delete_user(1)
print(get_users())

四、总结

通过本文的实战教程,你已经掌握了Python与MySQL、SQLite的基本操作。无论是处理大规模数据还是轻量级应用,Python与数据库的结合都能为你提供强大的支持。希望你能在此基础上,进一步探索更多高级功能,提升自己的开发能力。

Happy Coding! 🐍📊

你可能想看:
« 上一篇
下一篇 »

相关推荐

python爬虫教程PDF,Python爬虫书PDF

2026年09月02日

32阅读

外国教程python,python编程教学视频

2026年09月02日

27阅读

python简明教程沈洁元,python详细基础教程

2026年09月02日

21阅读

python库包教程,python 包

2026年09月02日

27阅读

python教程大全集,python教程600集

2026年09月02日

27阅读

python入门教程完整版,python零基础入门全套教程视频

2026年09月02日

23阅读