17. Python 数据库操作之MySQL和SQLite实例
import sqlite3
import mysql.connector
from mysql.connector import Error
# SQLite数据库操作
def sqlite_example():
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS stocks
(date text, trans text, symbol text, qty real, price real)''')
cursor.execute("INSERT INTO stocks VALUES ('2020-01-05', 'BUY', 'RHAT', 100, 35.14)")
cursor.close()
conn.commit()
conn.close()
# MySQL数据库操作
def mysql_example():
try:
conn = mysql.connector.connect(host='localhost',
database='employees',
user='username',
password='password')
if conn.is_connected():
cursor = conn.cursor()
cursor.execute("SELECT first_name, last_name FROM employees WHERE employee_id = %s", (100,))
print(cursor.fetchall())
cursor.close()
except Error as e:
print(e)
finally:
if conn is not None and conn.is_connected():
conn.close()
# 调用函数
sqlite_example()
mysql_example()
这段代码展示了如何使用Python进行SQLite和MySQL数据库的基本操作,包括创建表格、插入数据以及执行查询。代码中使用了sqlite3
和mysql.connector
模块,并对数据库连接进行了异常处理。
评论已关闭