Issue with connection to the database through VS code

Prchalová Tereza 40 Reputation points
2025-08-05T10:29:26.58+00:00

Hi,

My Python code is supposed to access a database and perform a check, but the behavior is inconsistent — sometimes it works, and other times it doesn’t. I’m not sure what’s causing the issue.

I’ve already added retries, delays, and other safeguards. I don’t think it’s a connection or internet problem, because I’m running the script in the same environment and at the same time, yet some attempts fail while others succeed.

Is there something I might be missing? Currently, I’m using 10 retries with a 10-second delay between each attempt.

Developer technologies | Visual Studio | Debugging
0 comments No comments
{count} votes

Accepted answer
  1. Varsha Dundigalla(INFOSYS LIMITED) 795 Reputation points Microsoft External Staff
    2025-08-06T08:22:38.94+00:00

    Thank you for reaching out. Please find the steps below.

    Troubleshooting Database Connection Issues in VS Code

    1. Run Outside VS Code (to isolate the problem)\ Run your script from the system terminal:

    python /path/to/your/script.py
     
    

    If it works fine outside VS Code, the issue is likely VS Code-specific. If it still fails, the issue is likely with the system, environment, or database server.

    2. Fix Common VS Code Problems
    A. Python Environment Issues Press Ctrl+Shift+P → Choose Python: Select Interpreter Make sure the Python version used by VS Code is the one you expect. Reinstall DB drivers in the correct environment:
    pip install --force-reinstall psycopg2 pyodbc mysql-connector-python  
    B. Extensions Conflict\ Disable all extensions → Reload VS Code\ Re-enable extensions one by one, especially Python, database, or remote tools\
    C. Debug Console vs Terminal\ Avoid running code in the Debug Console.\ Use the Integrated Terminal by setting this in launch.json:

    "console": "integratedTerminal"
    

    3. Detect Unclosed Database Connections\ Add this to your script to check for leaked connections:

    import psutil, os
    proc = psutil.Process(os.getpid())
    print(f"Open files/connections: {len(proc.open_files())}")
    

    4. Improve Retry Logic for VS Code Environments\ Use exponential backoff for retrying connections:

    import time
    from psycopg2 import OperationalError, InterfaceError
    
    for i in range(15):
        try:
            # Your connection code here
            break
        except (OperationalError, InterfaceError) as e:
            if "connection already closed" in str(e):
                print(f"Retry {i+1} due to closed connection.")
                time.sleep(min(60, 2 ** i))
            else:
                raise
    

    5. Check Environment from VS Code Terminal\ Run these commands to check connectivity:

    ping your-database-host.com
    nslookup your-database-host.com
    telnet your-database-host.com 5432  # Replace with your DB port
    

    6. Workspace Configuration Fixes\ Add this to .vscode/settings.json:

    {
      "terminal.integrated.env.linux": {
        "PYTHONUNBUFFERED": "1"
      },
      "python.terminal.activateEnvironment": true,
      "python.languageServer": "Pylance"
    }
    
    

    7. Reset or Clean VS Code\ Clear Python cache:

    rm -rf ~/.vscode/extensions/ms-python.python-*/pythonFiles
    

     ```

    Reset VS Code settings: Press Ctrl+Shift+P → SelectPreferences: Reset Settings

    What to Monitor
    Errors in View → Output → Python panel
    Error patterns (e.g., happens after a few minutes?)
    CPU/memory usage during failures
    Error messages like [Errno 111] Connection refused or[Errno 104] Connection reset

    If the Issue Continues, Please share:

    • Which database you're using (PostgreSQL, MySQL, SQLite, etc.)
    • The output of this in VS Code:
      import sys print(sys.executable) 
    • The full error message from the failing attempt

    Let me know If you need help with this


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.