使用Python进行数据库连接与操作SQLite和MySQL
import sqlite3
import mysql.connector
from mysql.connector import Error
# 连接SQLite数据库
def connect_sqlite(database):
try:
conn = sqlite3.connect(database)
return conn
except sqlite3.Error as e:
print(e)
return None
# 连接MySQL数据库
def connect_mysql(host, database, user, password):
try:
conn = mysql.connector.connect(
host=host,
database=database,
user=user,
password=password
)
return conn
except Error as e:
print(e)
return None
# 使用SQLite数据库
def use_sqlite(conn):
if conn is not None:
cursor = conn.cursor()
cursor.execute("SELECT * FROM some_table")
rows = cursor.fetchall()
for row in rows:
print(row)
conn.close()
# 使用MySQL数据库
def use_mysql(conn):
if conn is not None:
cursor = conn.cursor()
cursor.execute("SELECT * FROM some_table")
rows = cursor.fetchall()
for row in rows:
print(row)
conn.close()
# 示例使用
if __name__ == '__main__':
sqlite_conn = connect_sqlite('database.db')
use_sqlite(sqlite_conn)
mysql_conn = connect_mysql('localhost', 'mydatabase', 'myuser', 'mypassword')
use_mysql(mysql_conn)
这段代码展示了如何使用Python连接SQLite和MySQL数据库,并执行一个简单的查询操作。代码中包含了错误处理,以确保在无法建立连接时能够给出清晰的反馈。在实际应用中,你需要根据自己的数据库配置和需求来调整连接参数和执行的SQL语句。
评论已关闭