db_info.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import pyodbc
  2. class DatabaseInfo:
  3. conn: pyodbc.Connection
  4. def __init__(self):
  5. self._conn = pyodbc.connect("DSN=GC;UID=sa;PWD=Mffu3011#")
  6. def databases(self):
  7. res = self._conn.execute(
  8. "SELECT name FROM master.sys.databases WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb')"
  9. )
  10. return res.fetchall()
  11. def table_size(self, database):
  12. self._conn.execute(f"USE {database}")
  13. res = self._conn.execute(
  14. """
  15. SELECT db_name() as DatabaseName, s.name AS SchemaName, t.name AS TableName, p.rows AS RowCounts,
  16. SUM(a.total_pages) * 8 AS TotalSpaceKB,
  17. SUM(a.used_pages) * 8 AS UsedSpaceKB,
  18. (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB,
  19. u.last_user_update AS LastChanged
  20. FROM sys.tables AS t
  21. INNER JOIN sys.indexes AS i ON t.object_id = i.object_id
  22. INNER JOIN sys.partitions AS p ON i.object_id = p.object_id AND i.index_id = p.index_id
  23. INNER JOIN sys.allocation_units AS a ON p.partition_id = a.container_id
  24. LEFT OUTER JOIN sys.schemas AS s ON t.schema_id = s.schema_id
  25. LEFT OUTER JOIN sys.dm_db_index_usage_stats AS u ON t.object_id = u.object_id
  26. WHERE (t.name NOT LIKE 'dt%') AND (t.is_ms_shipped = 0) AND (i.object_id > 255)
  27. GROUP BY s.name, t.name, p.rows
  28. ORDER BY 1, 2, 3"""
  29. )
  30. return res.fetchall()