Skip to main content

Getting SQL Server Database Size using Python on Windows

Pre-requisites:

1.       Install SQL Server or an Azure SQL Database: I have tested it with SQL Server 2012 installation

2.       Get Python: https://www.python.org/downloads/

3.       Get Microsoft ODBC Driver 11 or 13 for SQL Server Windows:  

4.       Install 'Pyodbc' library using pip or any other package manager of your choice
 

Here are the main parts of Python Script that fetches DB size - 
  •  Import Pyodbc library
import pyodbc

  • Define database variables
server = <ServerName>
database = <DBName>
username = <UserName>
password = <Password>
  •  Define Database Connection String
cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+'; 
                                        DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()   
  • Define query to calculate DB size in SQL Server
cursor.execute( 
"SELECT [TYPE]= A.TYPE_DESC
       ,[FILE_Name] = A.name
       ,[FILEGROUP_NAME] = fg.name
       ,[File_Location] = A.PHYSICAL_NAME
       ,[FILESIZE_MB] = CONVERT(DECIMAL(10,2),A.SIZE/128.0)
       ,[USEDSPACE_MB] = CONVERT(DECIMAL(10,2),A.SIZE/128.0 - ((SIZE/128.0)  
- CAST(FILEPROPERTY(A.NAME, 'SPACEUSED') AS INT)/128.0))
       ,[FREESPACE_MB] = CONVERT(DECIMAL(10,2),A.SIZE/128.0 - CAST(FILEPROPERTY(A.NAME, 'SPACEUSED') AS INT)/128.0)
       ,[FREESPACE_%] = CONVERT(DECIMAL(10,2),((A.SIZE/128.0 - CAST(FILEPROPERTY(A.NAME,    'SPACEUSED') AS INT)/128.0)/(A.SIZE/128.0))*100)
       ,[AutoGrow] = 'By ' + CASE is_percent_growth WHEN 0 THEN CAST(growth/128 AS VARCHAR(10)) + ' MB -'
        WHEN 1 THEN CAST(growth AS VARCHAR(10)) + '% -' ELSE '' END + CASE max_size WHEN 0 THEN 'DISABLED' WHEN -1 THEN ' Unrestricted' ELSE ' Restricted to ' + CAST(max_size/(128*1024) AS VARCHAR(10)) + ' GB' END + CASE is_percent_growth WHEN 1 THEN ' [autogrowth by percent, BAD setting!]' ELSE '' END
        FROM sys.database_files A LEFT JOIN sys.filegroups fg ON A.data_space_id = fg.data_space_id order by A.TYPE desc, A.NAME;")
  • Fetch result and print Database size
row = cursor.fetchone() 
print(row) 
print("File Size is '%s' MB" % row[4]) 
print("Used Spac is '%s' MB" % row[5]) 
print("Free Space is '%s' MB" % row[6])

Comments

Popular posts from this blog

Solving PyCharm bug: "Python helpers are not copied yet..."

I have been using PyCharm Professional to run and debug Python code from my Windows machine to a remote Linux device. There are some other tools available for the same purpose (e.g. Python Tool for Visual Studio 2017). But in my opinion, PyCharm Professional stands out among its counterparts as it comes with a "All Batteries Included" setup. Once you configure remote Python interpreter in PyCharm, then it works out of the box. However, today after upgrading to PyCharm Professional 2018.2.1, I could not run my Python script on remote device. The execution always failed with below error - "Error running 'hello': Python helpers are not copied yet to the remote host. Please wait until remote interpreter initialization finishes." To solve this issue, I had to remove the ".pycharm_helpers " folder from the remove device and then restart PyCharm so that the folder is re-created and files are copied again. Here are the steps with comma

Customized Crosshair with OxyPlot charting library

I am using Oxyplot to draw heatmap for a WPF project and needed to draw a crosshair that moves according to user clicks. Since I couldn't find any good example or documentation on the topic, I made a small hack by using LineAnnotations and by over-riding Oxyplot mouse click event. Here is the sample code using WPF with MVVM pattern- MainWindow.xaml <Grid>         <oxy:Plot x:Name="CrossHairPlot">             <oxy:Plot.Axes>                 <oxy:LinearAxis Key="MyXAxis" Position="Bottom" IsZoomEnabled="False"/>                 <oxy:LinearAxis Key="MyYAxis" Position="Left" IsZoomEnabled="False"/>                 <oxy:LinearColorAxis Key="ZAxis" Position="Top" LowColor="Black"                                                                                      HighColor="White" PaletteSize="300">                     <G

Solving ‘Could not resolve host: github.com’ issue

Recently I ran into this issue while trying to clone one of my own repository from GitHub C:\GitHub\FS> git clone https://github.com/<username>/FS.git Cloning into 'FS'... fatal: unable to access 'https://github.com/<username>/FS.git/': Could not resolve host: github.com At first I thought that this could be due to some proxy setting. So I tried to unset it by executing below command - C:\GitHub\FS> git config --global --unset https.proxy But that didn’t fix the problem and I was still getting the same error. As it turned out later, the culprit was my VPN connection. Turning off the VPN fixed the issue. For the records, I was using ‘Surfshark’ on my Windows 10 laptop.