views:

398

answers:

2

I met with a strange problem about sqlite3. I obtained different connections of the same database file using open() method. connection 1 begins a transaction, and connection 2 begins another transaction, which is to update several records of a table. Then connection 1 commit the transaction, followed by connection 2 commit its transaction. But I found that the update command of connection 2 is never actually update the record in the database. There is no exception throwed during this procedure. I don't know why the problem occurs. Can anyone explain the reason to me?

Thank you very much!

+1  A: 

If you read the SQLite documentation, you will see that it supports multiple connections for reading only, you cannot write to the database from mulitple connections, because it's not designed for that.

http://www.sqlite.org/faq.html#q5

rustyshelf
You can, however, have two concurrent write transactions, which is what is causing the problem.
Doug Currie
So, if there is a transaction which is doing a write operation to the database, any other write operations can't modify the database, no matter these operations are within a transaction or not?
Can I do a select operation when there is another connection doing a write operation(insert, update) at the same time?
Transactions don't modify the database (as far as other transactions can tell) until COMMIT. So, multiple transactions can be "doing write operations" at the same time, but only one will succeed at COMMIT. All operations are in a transaction; it may be implicit.
Doug Currie
You can do SELECT operations on the database while another transaction is doing write operations. The SELECT will not see the writes (unless you are using a shared cache in read-uncommitted mode; see http://www.sqlite.org/sharedcache.html).
Doug Currie
+1  A: 

Unless you use BEGIN IMMEDIATE to initiate your transactions, you run the risk of having to rollback and retry them. A BEGIN does not do any locking; subsequent UPDATE or INSERT gets the lock, and you need to check the result code to see if they fail. See this page on transactions and this one on locks.

Doug Currie