Python数据库编程指南:连接与操作SQLite与MySQL
import sqlite3
import pymysql
# 连接SQLite数据库
sqlite_connection = sqlite3.connect('example.db')
sqlite_cursor = sqlite_connection.cursor()
# 连接MySQL数据库
mysql_connection = pymysql.connect(host='localhost', user='user', password='passwd', db='example')
mysql_cursor = mysql_connection.cursor()
# SQLite操作示例
sqlite_cursor.execute("""CREATE TABLE IF NOT EXISTS sqlite_table (id INTEGER PRIMARY KEY, name TEXT)""")
sqlite_connection.commit()
sqlite_cursor.execute("INSERT INTO sqlite_table (name) VALUES (?)", ("Python",))
sqlite_connection.commit()
sqlite_cursor.execute("SELECT * FROM sqlite_table")
print(sqlite_cursor.fetchall())
# MySQL操作示例
mysql_cursor.execute("""CREATE TABLE IF NOT EXISTS mysql_table (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255))""")
mysql_connection.commit()
mysql_cursor.execute("INSERT INTO mysql_table (name) VALUES (%s)", ("Python",))
mysql_connection.commit()
mysql_cursor.execute("SELECT * FROM mysql_table")
print(mysql_cursor.fetchall())
# 关闭数据库连接
sqlite_connection.close()
mysql_connection.close()
这段代码展示了如何使用Python进行SQLite和MySQL数据库的连接和基本操作,包括创建表、插入数据和查询数据。代码简洁,注重于展示核心功能。
评论已关闭