Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are multiple problems with the given example. I will address them one by one. </p> <ul> <li>There is no error checking. We either need to use the try/except/finally construct or use the <strong>with</strong> keyword.</li> <li>Python methods are not like C# properties. You are not running the <code>execute()</code> method, you are assigning some string to an object. (In Python, methods are objects too.)</li> <li>Very important is that your code is subject to <strong>SQL Injection attacks</strong>. We should never build SQL statements using Python string operations. We should always use <strong>placeholders</strong>.</li> <li>The example is incomplete. Which leads to a tricky issue. Supposing, that there was a <code>CREATE TABLE</code> statement then a new <strong>implicit transaction</strong> would be created. And a <code>commit()</code> statement must be issued to save the data to the database file. In SQLite, any statement other than <code>SELECT</code> starts an implicit transaction. (Some databases, like MySQL, are in the autocommit mode by default. This is not true for SQLite.)</li> </ul> <p>Here is a proper working example, which will write a LibreOffice document to a Docs table of an SQLite database:</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import sqlite3 as lite fl = open('book.odt', 'rb') with fl: data = fl.read() con = lite.connect('test.db') with con: cur = con.cursor() cur.execute("CREATE TABLE IF NOT EXISTS Docs(Data BLOB)") sql = "INSERT INTO Docs(Data) VALUES (?)" cur.execute(sql, (lite.Binary(data), )) </code></pre> <p>The book.odt file is located in the current working directory. We did not call the commit() method manually, since this is handled by the with keyword behind the scenes. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload