Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlite insert query not working with python?

Tags:

python

sqlite

I have been trying to insert data into the database using the following code in python:

import sqlite3 as db conn = db.connect('insertlinks.db') cursor = conn.cursor() db.autocommit(True) a="asd" b="adasd" cursor.execute("Insert into links (link,id) values (?,?)",(a,b)) conn.close() 

The code runs without any errors. But no updation to the database takes place. I tried adding the conn.commit() but it gives an error saying module not found. Please help?

like image 549
Saurabh Avatar asked Mar 18 '14 19:03

Saurabh


People also ask

How manually insert data in SQLite database?

If you want to inset the data manually(fully graphical) do the following: Go to the DDMS perspective. File explorer (tab-menu) Locate your db (/data/data/com.

How will you connect Python with SQLite database to create and insert records into database?

Inserting data using python Import sqlite3 package. Create a connection object using the connect() method by passing the name of the database as a parameter to it. The cursor() method returns a cursor object using which you can communicate with SQLite3.


2 Answers

You do have to commit after inserting:

cursor.execute("Insert into links (link,id) values (?,?)",(a,b)) conn.commit() 

or use the connection as a context manager:

with conn:     cursor.execute("Insert into links (link,id) values (?,?)", (a, b)) 

or set autocommit correctly by setting the isolation_level keyword parameter to the connect() method to None:

conn = db.connect('insertlinks.db', isolation_level=None) 

See Controlling Transactions.

like image 87
Martijn Pieters Avatar answered Sep 22 '22 16:09

Martijn Pieters


It can be a bit late but set the autocommit = true save my time! especially if you have a script to run some bulk action as update/insert/delete...

Reference: https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.isolation_level

it is the way I usually have in my scripts:

def get_connection():     conn = sqlite3.connect('../db.sqlite3', isolation_level=None)     cursor = conn.cursor()     return conn, cursor  def get_jobs():     conn, cursor = get_connection()      if conn is None:         raise DatabaseError("Could not get connection") 

I hope it helps you!

like image 30
Eduardo Cerqueira Avatar answered Sep 20 '22 16:09

Eduardo Cerqueira