1
votes
conn = sqlite3.connect(self.__database_name)
c = conn.cursor()
sql = 'INSERT OR IGNORE INTO ' + self.__article_url_table_name + ' (url) values (%s)' % (href)
c.execute(sql)
conn.commit()

I get the following error in the line where I call: c.execute(sql)

sqlite3.OperationalError: near "/": syntax error

The url variable is a string which contains a url like: https://www.foo.com/bar.html

What is the error in my code ?

2
Just read the introduction section of docs.python.org/3/library/sqlite3.html which already tells you why you're doing it double wrong. - Stefan Pochmann

2 Answers

5
votes

You should not be using string interpolation to write SQL queries. Quite apart from the problem you're having, it leaves you open to SQL injection. Use parameters instead:

sql = 'INSERT OR IGNORE INTO ' + self.__article_url_table_name + ' (url) values (?)'
c.execute(sql, (href,))
5
votes

The error is that you're not using the db-api the right way. You are building the sql query using string formatting:

sql = "INSERT OR IGNORE INTO some_table (url) values (%s)" % href

This leads to two problems.

The first one is correct handling of quoting and escaping. In your case you could work around by adding quotes around the format sign ie:

sql = "INSERT OR IGNORE INTO some_table (url) values ('%s')" % href

but this will still break if href contains quotes.

The second and much more important problem is that your code is now opened to sql injection attacks.

The correct use of the db-api will solve both problems: just use your dp-api module's placeholder (for sqlite it's a '?') in the sql string and pass arguments to the cursor.execute() call. Your db-api module will then take care of proper quoting / escaping AND will properly sanitize your arguments to prevent sql injections:

sql = "INSERT OR IGNORE INTO some_table (url) values (?)"
c.execute(sql, (href,))

Note that this doesn't work for table names, only for values passed to a select, insert or delete query, so in your case you'll still have to use string formatting for the table name:

sql = "INSERT OR IGNORE INTO {} (url) values (?)".format(self.__article_url_table_name)
c.execute(sql, (href,))

Totally unrelated by I noticed you use the __private naming convention for your class attributes. This convention triggers a name-mangling mechanism that is mainly intended to prevent accidental override of some attribute. Practically, this is almost never needed (eventually for some implementation detail of a base class in a framework, and even then) and can be really annoying. The convention for "implementation attributes" is to use a single leading underscore, which is understood by all python programmers as "implementation detail, don't mess with this or you're on your own".