在实验室信息管理系统的实际使用中,有时需要对数据进行直接操作。本文基于一次从数据库中删除化合物的需求,探索如何绕过Web界面,通过编程方式连接至elabFTW的数据库,为后续可能的功能扩展奠定基础。
我们将演示如何使用Python,结合pymysql库,通过Docker容器的网络配置来建立与MySQL数据库的连接,并进行基础的查询操作。
环境与思路
elabFTW通常使用Docker进行部署,其数据库运行在一个独立的容器内。我们的核心思路是:利用docker的Python SDK获取目标容器的网络信息(如IP地址),然后使用pymysql建立连接。
核心代码实现
以下代码展示了如何定位容器IP并连接数据库,以及执行一些基础查询。
import pymysql
import docker
from docker.errors import NotFound
def test_mysql_connection():
client = docker.from_env()
try:
# 获取容器信息
container = client.containers.get('781888888e108')
# 通过容器IP连接
try:
networks = container.attrs['NetworkSettings']['Networks']
container_ip = list(networks.values())[0]['IPAddress']
conn2 = pymysql.connect(
host=container_ip,
port=3306,
user='root',
password='ixxxxxxxxxxxxx',
database='elabftw',
connect_timeout=5
)
print(f"✅ 通过容器IP {container_ip}:3306 连接成功")
return conn2
except Exception as e:
print(f"❌ 容器IP连接失败: {e}")
except NotFound:
print("❌ 容器不存在")
except Exception as e:
print(f"❌ 其他错误: {e}")
return None
def execute_mysql_queries(connection):
"""执行各种MySQL查询语句"""
try:
with connection.cursor() as cursor:
# 1. 显示所有表
print("\n" + "="*50)
print("1. 显示所有表")
print("="*50)
cursor.execute("SHOW TABLES;")
tables = cursor.fetchall()
for table in tables:
# 表名在第一个字段
table_name = table[0]
print(f" - {table_name}")
# 2. 查询特定表的数据(示例)
print("\n" + "="*50)
print("2. 查询表数据示例")
print("="*50)
# 如果有表,选择第一个表进行查询
if tables:
sample_table = tables[0][0]
print(f"查询表 '{sample_table}' 的前5条记录:")
try:
cursor.execute(f"SELECT * FROM `{sample_table}` LIMIT 5;")
rows = cursor.fetchall()
# 获取列名
column_names = [desc[0] for desc in cursor.description]
print("列名:", column_names)
# 显示数据
for i, row in enumerate(rows, 1):
print(f" {i}: {row}")
except Exception as e:
print(f" 无法查询表 {sample_table}: {e}")
# 提交事务(如果有更新操作)
# connection.commit()
print("\n✅ 所有查询执行完成")
except pymysql.MySQLError as e:
print(f"❌ 数据库错误: {e}")
connection.rollback()
except Exception as e:
print(f"❌ 其他错误: {e}")
connection = test_mysql_connection()
execute_mysql_queries(connection)
运行结果示例
执行上述代码,输出结果如下。成功连接后,首先列出了数据库中的所有表,然后查询了第一个表(示例中为api_keys)的前5条数据。
✅ 通过容器IP 192.168.128.3:3306 连接成功
==================================================
1. 显示所有表
==================================================
- api_keys
- audit_logs
- authfail
- compounds
- compounds2experiments
- compounds2experiments_templates
- compounds2items
- compounds2items_types
- compounds_fingerprints
- config
... (此处省略部分表名)
- users2team_groups
- users2teams
==================================================
2. 查询表数据示例
==================================================
查询表 'api_keys' 的前5条记录:
列名: ['id', 'name', 'hash', 'created_at', 'can_write', 'userid', 'team', 'last_used_at']
1: (11, 'ming', '$*********2', datetime.datetime(2023, 3, 27, 10, 8, 14), 1, 2, 2, None)
2: (16, 'v2', '$*********2', datetime.datetime(2025, 11, 26, 13, 47, 31), 1, 12, 3, datetime.datetime(2025, 11, 28, 20, 43, 36))
✅ 所有查询执行完成
后续扩展
基于此连接,我们可以进一步执行更复杂的SQL操作,例如创建新表、插入、更新或删除特定数据,从而为elabFTW实现官方未提供的定制化功能。这种直接操作MySQL数据库的方式在与各类后端系统集成时非常有用。
重要提示:elabFTW官方不推荐直接操作底层数据库,因为这可能破坏数据一致性并导致系统异常。在进行任何写操作前,务必备份数据,并充分理解表结构关系。