How to operate in a multithreaded database-multithreaded serial __ Database

Source: Internet
Author: User
Tags readable sqlite stub create database
premisesMost of the time we open the database directly under the main thread and manipulate the database, but if you encounter an encrypted database, such as a sqlcipher encrypted database, or a database that encrypts the field, you have to manipulate the database within the thread.

SolveAs you know, when you're working with a database in multithreading, you use the previous method in the respective threads: Instantiate a Sqliteopenhelper class, and then invoke the method in it. You'll find it in the back. Android.database.sqlite.SQLiteException:database is lockedSuch an exception. The reason is of course multithreading, caused by the shutdown exception, such as a thread of a query operation, opened the database, the B thread close, causing a thread error. to solve the same problem, a safer way is to use the form of a single instance to create a Sqliteopenhelper class or to implement a DAO class that is specific to database additions and deletions, and to add synchronizaed keywords to the method. Key code: STUDAO contains the operation statements on the database, with the lock on the method
Package Com.lingdududu.testSQLiteDao;
Import android.content.ContentValues;
Import Android.content.Context;
Import Android.database.Cursor;
Import Android.database.sqlite.SQLiteDatabase;
Import Android.os.Build;

Import Android.util.Log;

Import Com.lingdududu.testSQLiteDb.StuDBHelper;
	public class Studao {//Create Studbhelper object Studbhelper dbhelper = null;
	Get a readable sqlitedatabase object sqlitedatabase db = null;
	Cursor Cursor = null;

	static Studao Studao = null;
	Private String TABLE = "stu_table";

	Private String TAG = "Studao";

	Static Object lock = new Object (); public static Studao getinstance {if (Studao = = null) {synchronized (lock) {if (Studao = = nul
				L) {Studao = new Studao (context);
	}} return Studao;
		public void Destorydb () {//Closing database close ();
	Studao = null;
		Private Studao (Context context) {LOG.E (TAG, "--->>> studao");
		DBHelper = new Studbhelper (context, "stu_db", NULL, 1); if (build.version.
		Sdk_int >=) {dbhelper.getwritabledatabase (). enablewriteaheadlogging ();

	} Object Querylock = new Object ();
		Public synchronized void QueryTable () {//Get a writable database db = Dbhelper.getwritabledatabase ();  Parameter 1: Table name//Parameter 2: To display the column//parameter 3:where clause//Parameter 4:where clause corresponding to the condition value//Parameter 5: Group mode//parameter 6:having condition//Parameter 7: Sorting method cursor =
		Db.query (TABLE, new string[] {"id", "sname", "Sage", "Ssex"}, NULL, NULL, NULL, NULL, NULL);
			while (Cursor.movetonext ()) {String name = cursor.getstring (Cursor.getcolumnindex ("sname"));
			String age = cursor.getstring (Cursor.getcolumnindex ("sage"));
			String sex = cursor.getstring (Cursor.getcolumnindex ("Ssex"));
			int id = cursor.getint (cursor.getcolumnindex ("id"));
		SYSTEM.OUT.PRINTLN ("Query-------> +" ID: "+ ID +" "+" Name: "+ name +" "+" Age: "+ ages +" "+" Sex: "+ sex);

	//Close database This.close ();
		Public synchronized void QueryTable (int id) {//Get a writable database db = Dbhelper.getwritabledatabase (); ParameterNumber 1: Table name//Parameter 2: To display the column//parameter 3:where clause//Parameter 4:where clause corresponding to the condition value//Parameter 5: Group mode//parameter 6:having condition//Parameter 7: Sort method cursor = db. Query (TABLE, new string[] {"id", "sname", "Sage", "Ssex"}, "Id=?", new string[] {integer.tostring (ID)}, NULL,
		NULL, NULL);
			while (Cursor.movetonext ()) {String name = cursor.getstring (Cursor.getcolumnindex ("sname"));
			String age = cursor.getstring (Cursor.getcolumnindex ("sage"));
			String sex = cursor.getstring (Cursor.getcolumnindex ("Ssex"));
			int sid = Cursor.getint (Cursor.getcolumnindex ("id"));
		LOG.D (TAG, "ID:" + SID + "" + "Name:" + name + "" + "Age:" + ages + "" + "Sex:" + sex);
	//Close database This.close ();
		Public synchronized void updatetable (string id, string sage) {//Get a writable database db = Dbhelper.getwritabledatabase ();
		Contentvalues CV = new Contentvalues ();
		Cv.put ("Sage", Sage);
		Cv.put ("id", id); WHERE clause "?"
		is the placeholder symbol, corresponding to the "1", String whereclause = "id=?";
		String[] Whereargs = {string.valueof (id)}; Parameter 1 is to be moreThe new table name//Parameter 2 is a Contentvaleus object//Parameter 3 is WHERE clause db.update (table, CV, Whereclause, Whereargs);
	Close database This.close ();
		Public synchronized void inserttable (string id, string sage) {//Get a writable database db = Dbhelper.getwritabledatabase ();
		Generate Contentvalues Object//key: Column name, Value: Values to insert contentvalues CV = new Contentvalues ();
		To Contentvalues object to store data, key-value pair pattern cv.put ("id", id);
		Cv.put ("Sname", "xiaoming");
		Cv.put ("Sage", Sage);
		Cv.put ("Ssex", "male");
		Invokes the Insert method to insert the data into the database Db.insert ("stu_table", NULL, CV);
	Close database/Close database this.close ();
		Public synchronized void deletetable (int id) {//Get a writable database db = Dbhelper.getwritabledatabase ();
		String whereclauses = "id=?";
		String[] Whereargs = {string.valueof (id)};
		Call the Delete method to delete the data db.delete (TABLE, whereclauses, Whereargs);
	Close database This.close ();
		Public synchronized void Deletetable () {//db = Dbhelper.getwritabledatabase ();
		String sql = "DROP table if exists" +table; Db.execsql (SQL);
		Get a writable database of db = Dbhelper.getwritabledatabase ();

		Call the Delete method to delete the data db.delete (TABLE, NULL, NULL);
	Close database This.close ();
		public void Close () {if (db!= null) {db.close ();
		} if (cursor!= null) {cursor.close (); }
	}

}

To open the thread manipulation database in Sqliteactivitymulthread:
Package com.lingdududu.testSQLite;
Import Com.lingdududu.MyThreadPoolExecutor;
Import Com.lingdududu.testSQLiteDao.StuDao;

Import Com.lingdududu.testSQLiteDb.StuDBHelper;
Import android.app.Activity;
Import android.content.ContentValues;
Import Android.database.Cursor;
Import Android.database.sqlite.SQLiteDatabase;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.view.View.OnClickListener;

Import Android.widget.Button; * * @author Lingdududu */public class Sqliteactivitymulthread extends activity {/** Called when the activity is firs T created.
	* *///Declare each button private buttons insertdatabase;
	Private Button updateDatabase1;
	Private Button UpdateDatabase2;

	Private Button deletedatabase;
	int age;

	int id = 100;
		@Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);

		Setcontentview (R.layout.main_mul);
		Call the Creatview method Creatview ();
		Setlistener (); Mythreadpoolexecutor.getinstance (). Execute (New Runnable (){////@Override//public void Run () {//Studao.getinstance (Sqliteactivitymulthread.this). QueryTable ();
		// }
		// }); for (age = 0; age < age++) {//Mythreadpoolexecutor.getinstance (). Execute (new Runnable () {//@Override/
		/public void Run () {//Studao.getinstance (Sqliteactivitymulthread.this)//. Updatetable (Integer.tostring (age));
		// }
		// });
		}} @Override protected void OnDestroy () {studao.getinstance (sqliteactivitymulthread.this). Destorydb ();
	Super.ondestroy (); ///The method of obtaining the Button object via Findviewbyid private void Creatview () {insertdatabase = (Button) Findviewbyid (R.id.insertdatabas
		e);
		UpdateDatabase1 = (Button) Findviewbyid (R.ID.UPDATEDATABASE1);
		UpdateDatabase2 = (Button) Findviewbyid (R.ID.UPDATEDATABASE2);
	DeleteDatabase = (Button) Findviewbyid (r.id.deletedatabase);
			///For the button registers the Listener method private void Setlistener () {Insertdatabase.setonclicklistener (new Onclicklistener () {@Override public void OnClick (View v) {//TODO auto-generated Method Stub//inserttable id = 100;
					for (; ID < id++) {final int sid = ID;
					SYSTEM.OUT.PRINTLN ("------sid----" +SID);
					SYSTEM.OUT.PRINTLN ("------ID----" +id); Mythreadpoolexecutor.getinstance (). Execute (new Runnable () {@Override public void run () {Studao.getin
							Stance (Sqliteactivitymulthread.this). Inserttable (integer.tostring (SID), integer.tostring (SID));
						Studao.getinstance (sqliteactivitymulthread.this). QueryTable (SID);
				}
					});
		}
			}

		}); Updatedatabase1.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {//TODO Auto
				-generated method Stub id = 100;
					Updatetable for (; ID < id++) {final int sid = ID;
					SYSTEM.OUT.PRINTLN ("------sid----" +SID);
					SYSTEM.OUT.PRINTLN ("------ID----" +id); Mythreadpoolexecutor.getinstance (). Execute (new Runnable () {@OverRide public void Run () {studao.getinstance (sqliteactivitymulthread.this). Updatetable (Integer.tostr
							ING (SID), Integer.tostring (SID * 2));
						Studao.getinstance (sqliteactivitymulthread.this). QueryTable (SID);
					}
					});  Mythreadpoolexecutor.getinstance (). Execute (new Runnable ()//{////@Override//public void run ()
					{//Studao.getinstance (Sqliteactivitymulthread.this). deletetable (ID);
				// }
					// });
		}
			}
		}); Updatedatabase2.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {//TODO Auto
				-generated method Stub id = 100;
					for (; ID < id++) {final int sid = ID;
					SYSTEM.OUT.PRINTLN ("------sid----" +SID);
					SYSTEM.OUT.PRINTLN ("------ID----" +id); Mythreadpoolexecutor.getinstance (). Execute (new Runnable () {@Override public void run () {Studao.getin
								Stance (Sqliteactivitymulthread.this)	. updatetable (integer.tostring (SID), Integer.tostring (SID * 3));
						Studao.getinstance (sqliteactivitymulthread.this). QueryTable (SID);
					}
					});  Mythreadpoolexecutor.getinstance (). Execute (new Runnable ()//{////@Override//public void run ()
					{//Studao.getinstance (Sqliteactivitymulthread.this). deletetable (ID);
				// }
					// });
		}
			}

		}); Deletedatabase.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {//TODO auto- Generated method stub mythreadpoolexecutor.getinstance (). Execute (new Runnable () {@Override the public void run
					() {studao.getinstance (sqliteactivitymulthread.this). deletetable ();
			}
				});

	}

		}); }//Create Database Method class Createlistener implements Onclicklistener {@Override public void OnClick (View v) {//Create St Udbhelper object Studbhelper dbhelper = new Studbhelper (sqliteactivitymulthread.this, "stu_db", NULL, 1);
		Get a readable sqlitedatabase object sqlitedatabase db = Dbhelper.getreadabledatabase (); Method Class Updatelistener implements Onclicklistener {@Override public void OnClick (View v) {//number of}//Update database
			According to the library version of the update, from the original 1 into 2 studbhelper dbhelper = new Studbhelper (sqliteactivitymulthread.this, "stu_db", NULL, 2);
		Sqlitedatabase db = Dbhelper.getreadabledatabase (); }///Insert Data Method class Insertlistener implements Onclicklistener {@Override public void OnClick (View v) {StuD
			Bhelper dbhelper = new Studbhelper (sqliteactivitymulthread.this, "stu_db", NULL, 1);

			Get a writable database sqlitedatabase db = Dbhelper.getwritabledatabase ();
			Generate Contentvalues Object//key: Column name, Value: Values to insert contentvalues CV = new Contentvalues ();
			To the Contentvalues object holds the data, the key-value pair pattern cv.put ("id", 1);
			Cv.put ("Sname", "xiaoming");
			Cv.put ("Sage", 21);
			Cv.put ("Ssex", "male");
			Invokes the Insert method to insert the data into the database Db.insert ("stu_table", NULL, CV);
		Close database Db.close ();

}
	}	Method of querying data class Querylistener implements Onclicklistener {@Override public void OnClick (View v) {Studbhelper
			DBHelper = new Studbhelper (sqliteactivitymulthread.this, "stu_db", NULL, 1);
			Get a writable database sqlitedatabase db = Dbhelper.getreadabledatabase (); Parameter 1: Table name//Parameter 2: To display the column//parameter 3:where clause//Parameter 4:where clause corresponding to the condition value//Parameter 5: Group mode//parameter 6:having condition//Parameter 7: Sort by C Ursor cursor = db.query ("stu_table", new string[] {"id", "sname", "Sage", "Ssex"}, "Id=?", new string[] {"1"}, Nu
			ll, NULL, NULL);
				while (Cursor.movetonext ()) {String name = cursor.getstring (Cursor.getcolumnindex ("sname"));
				String age = cursor.getstring (Cursor.getcolumnindex ("sage"));
				String sex = cursor.getstring (Cursor.getcolumnindex ("Ssex"));
			SYSTEM.OUT.PRINTLN ("Query------->" + "Name:" + name + "" + "Age:" + ages + "" + "Sex:" + sex);
		//Close database Db.close (); }///Modify Data Method class Modifylistener implements Onclicklistener {@Override
		public void OnClick (View v) {studbhelper dbhelper = new Studbhelper (sqliteactivitymulthread.this, "stu_db",
			NULL, 1);
			Get a writable database sqlitedatabase db = Dbhelper.getwritabledatabase ();
			Contentvalues CV = new Contentvalues ();
			Cv.put ("Sage", "100"); WHERE clause "?"
			is the placeholder symbol, corresponding to the "1", String whereclause = "id=?";
			String[] Whereargs = {string.valueof (1)};
		Parameter 1 is the table name//parameter 2 to be updated is a Contentvaleus object//Parameter 3 is WHERE clause db.update ("stu_table", CV, Whereclause, Whereargs); The method for deleting data class Deletelistener implements Onclicklistener {@Override public void OnClick (View v) {StuD
			Bhelper dbhelper = new Studbhelper (sqliteactivitymulthread.this, "stu_db", NULL, 1);
			Get a writable database sqlitedatabase db = Dbhelper.getreadabledatabase ();
			String whereclauses = "id=?";
			String[] Whereargs = {string.valueof (2)};
		Call the Delete method to delete the data db.delete ("Stu_table", whereclauses, Whereargs); }
	}
}

To implement your own thread pool:
Package Com.lingdududu;
Import Java.util.concurrent.Executor;
Import Java.util.concurrent.LinkedBlockingQueue;
Import Java.util.concurrent.ThreadFactory;
Import Java.util.concurrent.ThreadPoolExecutor;
Import Java.util.concurrent.TimeUnit;

Import Java.util.concurrent.atomic.AtomicInteger; Threadpoolexecutor executor = new Threadpoolexecutor (2, 5, timeunit.milliseconds,//New linkedblocking

Queue<runnable> ());
	public class Mythreadpoolexecutor implements Executor {private static final int core_pool_size = 5;
	private static final int maximum_pool_size = 256;

	private static final int keep_alive = 1; private static final Threadfactory sthreadfactory = new Threadfactory () {private final Atomicinteger Mcount = new Atomi

		Cinteger (1); @Override public Thread Newthread (Runnable R) {return new thread (R, "Mythreadpoolexecutor #" + mcount.getandinc
		Rement ());

	}
	};
	Private final Threadpoolexecutor Mthreadpoolexecutor; private static MYTHREADPOolexecutor Mexecutor; public static Mythreadpoolexecutor getinstance () {if (Mexecutor = null) {return new Mythreadpoolexecutor (Core_pool
		_size);
	return mexecutor; Public mythreadpoolexecutor getinstance (int poolsize) {if (Mexecutor = = null) {return new Mythreadpoolexecutor (
		Poolsize);
	return mexecutor;
	Private Mythreadpoolexecutor () {this (core_pool_size); Private mythreadpoolexecutor (int poolsize) {mthreadpoolexecutor = new Threadpoolexecutor (poolsize, Maximum_pool
	_size, Keep_alive, Timeunit.seconds, New linkedblockingqueue<runnable> (), sthreadfactory);
	public int getpoolsize () {return mthreadpoolexecutor.getcorepoolsize ();
		public void setpoolsize (int poolsize) {if (Poolsize > 0) {mthreadpoolexecutor.setcorepoolsize (poolsize); } public boolean IsBusy () {return mthreadpoolexecutor.getactivecount () >= mthreadpoolexecutor. Getcorepools
	Ize (); @Override public void execute (final RunnAble R) {Mthreadpoolexecutor.execute (R);
 }
}

I don't know if you found out. In the above method of acquiring the database, I use the getwritabledatabase (), because if the database is upgraded, if a table is deleted, it happens to be the use of getreadabledatabase () The way you open the database, you will get an error because you do not have permission to create the Modify database. See my blog for details http://blog.csdn.net/u011484134/article/details/49795991
For the latter issue, I have not thought of a good solution, welcome to discuss.
Source CodeFree integral Download http://download.csdn.net/detail/u011484134/9289557


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.