B
B
Bogdan Karpov2018-05-12 13:48:34
Python
Bogdan Karpov, 2018-05-12 13:48:34

How to escape a string in python3 (sqlite3 module) to write to the database?

I am writing a script that periodically writes different strings to the database (sqlite) in which any character can be found ("2%\\, etc.) how can they be escaped with something like (sqlite_escape_string () like in PHP). I use python 3, sqlite3 module

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SagePtr, 2018-05-12
@SagePtr

Is it difficult to read the documentation ?

# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)

# Do this instead
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print(c.fetchone())

# Larger example that inserts many records at a time
purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
             ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
             ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
            ]
c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question