SQLCode=-905, SQLState=57014: File Locked by Another Process

Troubleshooting

SQLCode=-905, SQLState=57014: File Locked by Another Process

SQLCODE=-905, SQLSTATE=57014 is the error that stopped my entire Db2 migration cold—until I realized the database name in my connection string had a typo. 💻 The message screams "file locked," but nine times out of ten, it’s not actually a file issue. It’s a misconfiguration screaming for attention.

This error appears when Db2 can’t find the database you’re asking for, whether because the name is wrong, the database doesn’t exist, or your connection string points to a different environment. I’ve seen it trigger from missing objects, permission gaps, or even case-sensitivity issues in database names.

The fix isn’t always obvious—sometimes it’s as simple as double-checking a single character in your db2 connect command.

You’ll resolve it in under five minutes by verifying three things: the database name exists, your user has access, and your connection string matches the actual database. I’ll walk you through the exact checks—starting with the most common culprit—and show you how to confirm each step without guessing.

No more wasted hours chasing phantom locks.

Works for Db2 on Linux, Windows, or z/OS. The same principles apply whether you’re connecting locally or remotely. Let’s get this resolved—permanently.

Why it happens

When you encounter SQLCODE=-905, SQLSTATE=57014, it’s your database’s way of saying, “This file is already being used, and I can’t touch it!” The error occurs when a database process (like a query, backup, or utility) attempts to access a file—such as a table space, index, or log file—that’s currently locked by another process.

Let’s break down the real culprits behind this frustration.

🔒 Exclusive File Locks from Active Processes

Databases like IBM Db2 use file locking mechanisms to prevent corruption when multiple processes try to modify the same data.

If one process (e.g., a long-running query, a backup job, or even an idle connection) holds an exclusive lock on a file, other processes—including your current SQL command—will be blocked until the lock is released.

  • Long-running transactions: A user or application may have opened a transaction that hasn’t been committed or rolled back yet, keeping the file locked.
  • Backup or maintenance jobs: Tools like db2backup or db2move can lock files for extended periods while processing.
  • Stale connections: A disconnected or crashed application might leave a file locked indefinitely if the session isn’t properly terminated.

Pro tip: 💡 Use db2pd -locks to check which processes are holding locks on your files. Look for Lock Type = Exclusive entries.

🔄 Improperly Closed or Terminated Sessions

Not all locks are intentional. Sometimes, a process crashes, an application hangs, or a user forgets to close a connection—leaving the file locked in limbo. This is especially common in:

  • Unclean shutdowns: If a Db2 instance or server restarts abruptly, some locks may not be released properly.
  • Application bugs: A poorly written program might open a file but fail to release it, even after the user moves on.
  • Network issues: A dropped connection can leave a lock active if the database doesn’t detect the disconnection in time.

Pro tip: 🔥 Run db2 "SELECT * FROM SYSCAT.LOCKS WHERE LOCKTYPE = 'EXCLUSIVE'" to identify orphaned locks. If you find them, you may need to terminate the offending session with db2term or restart the Db2 subsystem.

🔧 Concurrent Database Utilities or Admin Tasks

Database administrators often run utilities that require exclusive access to files. If two tools try to use the same file simultaneously, one will get locked out. Common offenders include:

  • REORG or RUNSTATS: These maintenance tasks lock table spaces or indexes to rebuild them.
  • LOAD or IMPORT operations: Bulk data loads can hold locks for minutes or hours.
  • Db2 Command Center or GUI tools: Some admin interfaces lock files when performing operations like schema changes.

Pro tip: ✨ Schedule maintenance tasks during low-traffic periods to avoid conflicts. If you’re unsure who’s locking the file, check the APPLICATIONID in SYSCAT.LOCKS to trace it back to a user or job.

🚨 Filesystem-Level Locks (External to Db2)

Sometimes, the issue isn’t inside Db2 at all—it’s your operating system or filesystem playing hard to get. For example:

  • Filesystem corruption: If the file system (e.g., ext4, NTFS, or ZFS) marks a file as “in use” due to a crash, Db2 won’t be able to access it.
  • Antivirus or security software: Some tools lock database files for scanning, even if they’re not actively being modified.
  • Storage quotas or permissions: A user or process might lack write permissions, causing the OS to lock the file defensively.

Pro tip: 🌡️ Use OS-level tools like lsof (Linux/macOS) or handle.exe (Windows) to check which external process has the file open. Example:

lsof | grep "yourdatabasefile"

If you find a rogue process, terminate it or adjust your antivirus exclusions.

How to solve it

Encountering a SQLCode=-905, SQLState=57014 error means a file is locked by another process, causing your database operations to stall. Let’s break down the most effective solutions, organized by root cause, so you can resolve the issue quickly and prevent future disruptions.

###

🔥 Cause 1: Unclosed Database Connections

When applications or scripts fail to release file handles properly, they leave files locked even after the session ends. This is the most common culprit behind this error.

How to Fix It:

  • 🔍 Identify the culprit process: Use platform-specific tools to find the locking process:
    • Windows: Open Task Manager → Performance → Open Resource Monitor → CPU → Associated Handles and search for the locked file.
    • Linux/macOS: Run lsof | grep "filename" to list processes holding the file.
  • 👨‍💻 Terminate the rogue process: If the process is safe to kill (e.g., a hung script), end it via Task Manager or kill -9 [PID]. For critical services, restart the application gracefully instead.
  • 🛠️ Update connection handling: Ensure your code explicitly closes connections, commits transactions, or uses try-finally blocks (Java) or using statements (C#) to guarantee cleanup.
    // Example in Java:
    try (Connection conn = DriverManager.getConnection(url)) {
        // Database operations
    } // Connection auto-closes here
          

💡 Prevention Tips:

  • Implement connection pooling (e.g., HikariCP, DBCP) to manage resources efficiently.
  • Set timeouts for idle connections to force cleanup.
  • Use database-specific tools like IBM DB2’s db2pd to monitor active locks.

###

🍳 Cause 2: Explicit File Locks in Custom Code

Applications or scripts may intentionally lock files for temporary operations (e.g., backups, logs) but forget to release them. This often happens in custom utilities or legacy systems.

How to Fix It:

  • 🔍 Audit your codebase: Search for functions like flock() (Linux), LockFile() (Windows), or database-specific lock commands (e.g., LOCK TABLE in SQL). Flag any locks without corresponding unlock logic.
  • 🔄 Release locks programmatically: Add explicit unlock calls or use context managers (e.g., Python’s with statement) to ensure locks are released even if errors occur.
    // Python example:
    with open("data.txt", "r") as f:
        flock(f.fileno(), LOCKEX)  # Lock
        # ... operations ...
        # Lock auto-releases when exiting 'with' block
          
  • ⏰ Set lock timeouts: Configure locks to expire after a short duration (e.g., 30 seconds) to prevent indefinite blocking.

💡 Prevention Tips:

  • Use high-level database APIs (e.g., ORMs like SQLAlchemy) that handle locking internally.
  • Log lock acquisitions/releases for debugging (e.g., print("Lock acquired on [file]")).
  • Test edge cases (e.g., abrupt script termination) to ensure locks don’t linger.

###

👨‍🍳 Cause 3: Database-Specific Locking Issues

Some databases (e.g., DB2, Oracle, PostgreSQL) use internal locking mechanisms that can conflict with external processes. Corrupted metadata or misconfigured parameters may also trigger this error.

How to Fix It:

  • 🛠️ Restart the database service: For minor issues, a simple restart can clear stuck locks:
    # Linux (systemd):
    sudo systemctl restart db2
    net stop DB2 / y && net start DB2
          
  • 🗑️ Clear stale locks: Use database commands to release locks:
    • DB2: db2 "SELECT * FROM SYSCAT.LOCKS" to list locks, then db2 "CALL SYSPROC.SYSINVALIDATELOCKS" to clear them.
    • Oracle: ALTER SYSTEM KILL SESSION '[SID, SERIAL]' (identify sessions via V$SESSION).
    • PostgreSQL: SELECT pgterminatebackend([PID]) from pgstatactivity.
  • 🔧 Adjust database parameters: Tune settings like db2cf locklist (DB2) or sharedbuffers (PostgreSQL) to reduce contention. Check your database’s documentation for lock-related configs.

💡 Prevention Tips:

  • Schedule regular database maintenance (e.g., REORG in DB2, VACUUM in PostgreSQL) to prevent lock buildup.
  • Monitor lock waits using tools like db2pd -locks or pgstatactivity.
  • Avoid long-running transactions; break them into smaller batches.

###

🔪 Cause 4: Antivirus or Backup Tools Interfering

Security software or automated backups may lock database files during scans or snapshots, causing conflicts with your application.

How to Fix It:

  • 🛡️ Exclude database files: Add your database directory to your antivirus’s exclusion list (e.g., Windows Defender → Virus & Threat Protection → Manage Settings → Exclusions).
  • ⏰ Schedule backups during off-peak hours: Configure tools like db2backup or pg_dump to run when the database has minimal activity.
  • 🔄 Use snapshot-based backups: Opt for tools that create read-only snapshots (e.g., ZFS snapshots, Volume Shadow Copy Service) instead of locking files directly.

💡 Prevention Tips:

  • Test backup tools in a staging environment to ensure they don’t cause locks.
  • Use database-native backup utilities (e.g., db2 backup db) instead of generic file-copy tools.

###

⏰ Cause 5: Filesystem or Storage Corruption

Underlying filesystem issues (e.g., permissions, disk errors) can prevent files from being unlocked properly, even after the process ends.

How to Fix It:

  • 🔍 Check filesystem health: Run fsck (Linux) or chkdsk (Windows) to repair errors:
    # Linux:
    sudo umount /path/to/db
    sudo fsck -f /dev/sdX
          
  • 🔄 Remount or reboot: If the filesystem is read-only, remount it with rw

Frequently asked questions

1

Why does SQLCODE=-905, SQLSTATE=57014 appear when my database name seems correct?

This error often occurs due to case sensitivity issues in your connection string or environment variables. Db2 treats database names as case-sensitive on Linux/Unix systems, so "MYDB" ≠ "mydb". Double-check your connection command or configuration file for exact name matches, including spaces or special characters.

2

How can I check if another process is actually holding the lock?

Use Db2's built-in tools to investigate. Run db2pd -locks to see active locks, then check db2 "SELECT * FROM SYSCAT.LOCKS" for exclusive locks on your files. For OS-level checks, try lsof | grep "yourdatabasefile" (Linux/macOS) or Resource Monitor (Windows).

3

Will restarting the Db2 service always fix this error?

Not necessarily—restarting clears active locks but won't resolve underlying issues like permission problems or connection string errors. Use it as a temporary fix while you investigate the root cause. Always verify your database name, user permissions, and connection parameters first.

4

Can antivirus software cause SQLCODE=-905 errors?

Many antivirus programs lock database files during scans, even if they're not actively being modified. Add your Db2 data directory to your antivirus exclusions immediately. For Windows, check Defender's "Virus & Threat Protection" settings under exclusions.

5

What's the safest way to terminate a process holding a lock?

First identify the process using db2pd -locks or OS tools. For non-critical processes, use kill -9 [PID] (Linux) or Task Manager (Windows). For database connections, prefer db2term or CALL SYSPROC.SYSINVALIDATELOCKS in Db2 to avoid corrupting transactions.

★★★★★4.5(13 reviews)
Categories Troubleshooting