python-3.xdatabasedebuggingsqlite3-python

How to add a file path into the SQLite3 database without experiencing sqlite3.InterfaceError?


Here's my code:

import sqlite3
from pathlib import WindowsPath

#Create database
conn = sqlite3.connect('file_path.db')
cursor = conn.cursor()

cursor.execute('''
    CREATE TABLE IF NOT EXISTS paths (
        id INTEGER PRIMARY KEY,
        file_path TEXT NOT NULL
    )
''')

cursor.execute('SELECT * FROM paths WHERE id = 1')

#Read input
input_path = input('enter file path: ')
path = WindowsPath(input_path.replace('"', ''))


#insert path
cursor.execute('INSERT INTO paths (id, file_path) VALUES (1, ?)', (path,))

conn.commit()

With the input something like:

enter file path: C:\Users\User\File

The following error pops up:

    cursor.execute('INSERT INTO paths (id, file_path) VALUES (1, ?)', (path,))
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.

Anyone know how to resolve this? The end goal is to store this file path into the database so I can use it later on.


Solution

  • The problem isn't that it is a file path the problem is that it is a WindowsPath. sqlite is expecting a string and instead it is getting and object of type WindowsPath and doesn't know what to do with it, hence the error.

    Simply wrapping path in a str will solve your issue.

    Example:

    cursor.execute('INSERT INTO paths (id, file_path) VALUES (1, ?)', (str(path),))