Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android SQLite 使用實例

android SQLite 使用實例

編輯:關於Android編程

Android作為目前主流的移動操作系統,完全符合SQLite占用資源少的優勢,故在Android平台上,集成了一個嵌入式關系型數據庫—SQLite。如果想要開發 Android 應用程序,需要在 Android 上存儲數據,使用SQLite 數據庫是一種非常好的選擇。在一般程序中使用數據庫的過程都可以框架化,套路化,實例如下:


表說明:

1.班級 classes:

class_id 主鍵 class_name

2.學生 students:

student_id 主鍵 student_name score class_id 外鍵


創建表:

CREATE TABLE classes(class_id varchar(10) primary key , class_name varchar(20))


CREATE TABLE students(student_id varchar(10) primary key ,

student_name varchar(20) ,
score varchar(4) ,
class_id varchar(10),

foreign key (class_id) references classes(class_id) on delete cascade on update cascade )





1. 繼承擴展 SQLiteOpenHelper 創建數據庫和對應表

package com.tang.databasedemo;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBHelper extends SQLiteOpenHelper
{

	public DBHelper(Context context) {
		super(context, "info.db", null, 1);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) 
	{
		// TODO Auto-generated method stub
		String classesSQL = "CREATE TABLE classes(class_id varchar(10) primary key , " +
        		"class_name varchar(20))";
		
		String studentsSQL = "CREATE TABLE students(student_id varchar(10) primary key , " +
        		"student_name varchar(20) ,score varchar(4) ,class_id varchar(10), " +
        		"foreign key (class_id) references classes(class_id) " +
        		"on delete cascade on update cascade )";
		db.execSQL(classesSQL);
		Log.d("my", "create table classes:"+classesSQL);
		db.execSQL(studentsSQL);
		Log.d("my", "create table students:"+studentsSQL);
		
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
	{
		// TODO Auto-generated method stub
		
	}

}

2. 創建學生(Class)學生(Student)實體

package com.tang.databasedemo;
import android.util.Log;
public class Class 
{
	private String classId;
	private String className;
	
	public String getClassId() {
		return classId;
	}
	public void setClassId(String classId) {
		this.classId = classId;
	}
	public String getClassName() {
		return className;
	}
	public void setClassName(String className) {
		this.className = className;
	}
	public String toString() {
		return "Class--->"+"classId:"+classId+"  className:"+className;

	}
}

package com.tang.databasedemo;
public class Student 
{
	private String studentId;
	private String studentName;
	private String score;
	private String classId;
	
	public String getStudentId() {
		return studentId;
	}
	public void setStudentId(String studentId) {
		this.studentId = studentId;
	}
	public String getStudentName() {
		return studentName;
	}
	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}
	public String getScore() {
		return score;
	}
	public void setScore(String score) {
		this.score = score;
	}
	public String getClassId() {
		return classId;
	}
	public void setClassId(String classId) {
		this.classId = classId;
	}
	public String  toString() 
	{
		return "Student--->"+"studentId:"+studentId+" studentName:"+studentName+" score:"+score+" classId:"+classId;
		
		
	}

}

3. 創建DBServer類,在該類中定義增刪改查等方法來操作數據庫

package com.tang.databasedemo;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DBServer 
{
	private DBHelper dbhelper;
	public DBServer(Context context)
	{
		 this.dbhelper = new DBHelper(context);
	}
	/**
	 * 添加班級
	 * @param entity
	 */
	public void addClass(Class entity)
	{
		  
		  SQLiteDatabase localSQLiteDatabase = this.dbhelper.getWritableDatabase();
		  Object[] arrayOfObject = new Object[2];
		  arrayOfObject[0] = entity.getClassId();
		  arrayOfObject[1] = entity.getClassName();
		  localSQLiteDatabase.execSQL("insert into classes(class_id,class_name) values(?,?)", arrayOfObject);
		  localSQLiteDatabase.close();
	}
	/**
	 * 添加學生
	 * @param entity
	 */
	public void addStudent(Student entity)
	{
		  
		  SQLiteDatabase localSQLiteDatabase = this.dbhelper.getWritableDatabase();
		  Object[] arrayOfObject = new Object[4];
		  arrayOfObject[0] = entity.getStudentId();
		  arrayOfObject[1] = entity.getStudentName();
		  arrayOfObject[2] = entity.getScore();
		  arrayOfObject[3] = entity.getClassId();
		  localSQLiteDatabase.execSQL("insert into students(student_id,student_name,score,class_id) values(?,?,?,?)", arrayOfObject);
		  localSQLiteDatabase.close();
	}
	
	/**
	 * 刪除一個班級
	 * 同時會刪除students中該班級的學生
	 * @param class_id
	 */
	public void deleteClass(String class_id)
	{
	    SQLiteDatabase localSQLiteDatabase = this.dbhelper.getWritableDatabase();
	    //設置了級聯刪除和級聯更新
	    //在執行有級聯關系的語句的時候必須先設置“PRAGMA foreign_keys=ON”
	    //否則級聯關系默認失效
	    localSQLiteDatabase.execSQL("PRAGMA foreign_keys=ON");
	    Object[] arrayOfObject = new Object[1];
	    arrayOfObject[0] =class_id;
	    localSQLiteDatabase.execSQL("delete from classes where class_id=?", arrayOfObject);
	    localSQLiteDatabase.close();
	}
	
	/**
	 * 刪除一個學生
	 * @param student_id
	 */
	public void deleteStudent(String student_id)
	{
	    SQLiteDatabase localSQLiteDatabase = this.dbhelper.getWritableDatabase();
	    Object[] arrayOfObject = new Object[1];
	    arrayOfObject[0] =student_id;
	    localSQLiteDatabase.execSQL("delete from students where student_id=?", arrayOfObject);
	    localSQLiteDatabase.close();
	}
	
	/**
	 * 修改學生信息
	* @param entity
	*/
   public void updateStudentInfo(Student entity)
   {
	   SQLiteDatabase localSQLiteDatabase = this.dbhelper.getWritableDatabase();
	   Object[] arrayOfObject = new Object[4];
	   
	   arrayOfObject[0] = entity.getStudentName();
	   arrayOfObject[1] = entity.getScore();
	   arrayOfObject[2] = entity.getClassId();
	   arrayOfObject[3] = entity.getStudentId();
   
	   localSQLiteDatabase.execSQL("update students set student_name=?,score=?,class_id=?  where student_id=?", arrayOfObject);
	   localSQLiteDatabase.close();
   }
	
	/**
	 * 使用班級編號查找該班級所有學生
	 * @param classId
	 * @return
	 */
	public List findStudentsByClassId(String classId)
	{
		  List localArrayList=new ArrayList();
		  SQLiteDatabase localSQLiteDatabase = this.dbhelper.getWritableDatabase();    
		  Cursor localCursor = localSQLiteDatabase.rawQuery("select student_id, student_name ,score  from students  " +
		  		"where class_id=?  order by score desc", new String[]{classId});
		 
		  while (localCursor.moveToNext())
		  {
			  Student temp=new Student();
			  temp.setStudentId(localCursor.getString(localCursor.getColumnIndex("student_id")));
			  temp.setStudentName(localCursor.getString(localCursor.getColumnIndex("student_name")));
			  temp.setScore(localCursor.getString(localCursor.getColumnIndex("score")));
			  temp.setClassId(classId);
		      localArrayList.add(temp);
		  }
		  localSQLiteDatabase.close();
		  return localArrayList;
	 }
	
	/**
	 * 使用班級名查找該班級所有學生
	 * @param className
	 * @return
	 */
	public List findStudentsByClassName(String className)
	{
		  List localArrayList=new ArrayList();
		  SQLiteDatabase localSQLiteDatabase = this.dbhelper.getWritableDatabase();    
		  Cursor localCursor = localSQLiteDatabase.rawQuery("select student_id, student_name,score,classes.class_id from students,classes" +
		  		" where students.class_id=classes.class_id and classes.class_name =?  order by score asc" , new String[]{className});
		 
		  while (localCursor.moveToNext())
		  {
			  Student temp=new Student();
			  temp.setStudentId(localCursor.getString(localCursor.getColumnIndex("student_id")));
			  temp.setStudentName(localCursor.getString(localCursor.getColumnIndex("student_name")));
			  temp.setScore(localCursor.getString(localCursor.getColumnIndex("score")));
			  temp.setClassId(localCursor.getString(3));
		      localArrayList.add(temp);
		  }
		  localSQLiteDatabase.close();
		  return localArrayList;
	 }
	/**
	 * 查找所有學生
	 * @param className
	 * @return
	 */
	public List findAllStudents()
	{
		  List localArrayList=new ArrayList();
		  SQLiteDatabase localSQLiteDatabase = this.dbhelper.getWritableDatabase();    
		  Cursor localCursor = localSQLiteDatabase.rawQuery("select * from students " +
		  		"where 1=1  order by score desc ", null);
		  while (localCursor.moveToNext())
		  {
			  Student temp=new Student();
			  temp.setStudentId(localCursor.getString(localCursor.getColumnIndex("student_id")));
			  temp.setStudentName(localCursor.getString(localCursor.getColumnIndex("student_name")));
			  temp.setScore(localCursor.getString(localCursor.getColumnIndex("score")));
			  temp.setClassId(localCursor.getString(localCursor.getColumnIndex("class_id")));
		      localArrayList.add(temp);
		  }
		  localSQLiteDatabase.close();
		  return localArrayList;
	 }
	
	
	/**
	 * 	取得所有班級
	 * @return
	 */
	public List findAllClasses()
	{
		  List localArrayList=new ArrayList();
		  SQLiteDatabase localSQLiteDatabase = this.dbhelper.getWritableDatabase();    
		  Cursor localCursor = localSQLiteDatabase.rawQuery("select * from classes " +
		  		"where 1=1", null);
		  while (localCursor.moveToNext())
		  {
			  Class temp=new Class();
			  temp.setClassId(localCursor.getString(localCursor.getColumnIndex("class_id")));
			  temp.setClassName(localCursor.getString(localCursor.getColumnIndex("class_name")));
		      localArrayList.add(temp);
		  }
		  localSQLiteDatabase.close();
		  return localArrayList;
	 }
	
	/**
	 * 成績最好
	 * @return
	 */
	public Student findMaxScoreStudent()
	{
		Student temp =new Student();
		SQLiteDatabase localSQLiteDatabase = this.dbhelper.getWritableDatabase();    
		Cursor localCursor = localSQLiteDatabase.rawQuery("select student_id,student_name,class_id,max(score)  from students  " +
		  		"where 1=1",null );
		localCursor.moveToFirst();
		temp.setStudentId(localCursor.getString(0));
		temp.setStudentName(localCursor.getString(1));
		temp.setClassId(localCursor.getString(2));
		temp.setScore(localCursor.getString(3));
		return temp;
	}
	

	
	/**
	 * 查找是否有該學生
	 * @param studentId
	 * @return
	 */
	public boolean isStudentsExists(String studentId)
	{
		  SQLiteDatabase localSQLiteDatabase = this.dbhelper.getWritableDatabase();    
		  Cursor localCursor = localSQLiteDatabase.rawQuery("select count(*)  from students  " +
		  		"where student_id=?", new String[]{studentId});
		  localCursor.moveToFirst();
		  if(localCursor.getLong(0)>0)
			  return true;
		  else
			  return false;
	 }
	
	/**
	 * 確認該班級是否存在
	 * @param classId
	 * @return
	 */
	public boolean isClassExists(String s)
	{
		  SQLiteDatabase localSQLiteDatabase = this.dbhelper.getWritableDatabase();    
		  Cursor localCursor = localSQLiteDatabase.rawQuery("select count(*)  from classes  " +
		  		"where class_id=? or class_name=?", new String[]{s,s});
		  localCursor.moveToFirst();
		  if(localCursor.getLong(0)>0)
			  return true;
		  else
			  return false;
	 }

}

4.調用DBServer裡的方法,操作數據

package com.tang.databasedemo;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.text.AlteredCharSequence;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {

	private List classData =new ArrayList();
	private List studentsData =new ArrayList();
	private static final String className ="A/B/C/D/E";
	private static final String studentName ="彭大/黃二/張三/李四/王五/鄭六/田七/周八/葉九/孔十/蕭十一";
	private DBServer db;
	private SharedPreferences share;
	private SharedPreferences.Editor editor;
	private String info ="";
	private EditText editText;
	private Button b,b1,b2,b3,b4,b5,b6;
	private EditText sId,sName,score,cId,cName;
	private Handler hander =new Handler()
	{
		@Override
		public void handleMessage(Message msg) 
		{
			// TODO Auto-generated method stub
			if(msg.what==0)
			{
				sId.setText("");
				sName.setText("");
				score.setText("");
				cName.setText("");
				cId.setText("");
			}
			else if(msg.what==1)
			{
				db.deleteClass((String)msg.obj);
				info += "刪除一個班級及班級裡面的學生:班級Id:"+(String)msg.obj;
				editText.setText(info);
			}
			
		}
		
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
		share = getSharedPreferences("DatabaseDamo", 0);
		editor =share.edit();
		db=new DBServer(this);
		if(share.getInt("times", 0)==0)
		{
			initDatabase();
			editor.putInt("times", 1);
			editor.commit();
		}
	}
	
	
	private void initView()
	{
		editText = (EditText) findViewById(R.id.info);
		sId = (EditText) findViewById(R.id.studentId);
		sName = (EditText) findViewById(R.id.studentName);
		score = (EditText) findViewById(R.id.score);
		cId = (EditText) findViewById(R.id.classId);
		cName = (EditText) findViewById(R.id.className);
		b =(Button) findViewById(R.id.button);
		b1 =(Button) findViewById(R.id.button1);
		b2 =(Button) findViewById(R.id.button2);
		b3 =(Button) findViewById(R.id.button3);
		b4 =(Button) findViewById(R.id.button4);
		b5 =(Button) findViewById(R.id.button5);
		b6 =(Button) findViewById(R.id.button6);
		b.setOnClickListener(this);
		b1.setOnClickListener(this);
		b2.setOnClickListener(this);
		b3.setOnClickListener(this);
		b4.setOnClickListener(this);
		b5.setOnClickListener(this);
		b6.setOnClickListener(this);
		
		
	}
	private void initDatabase()
	{
		info="";
		editText.setText("");
		String []classTemp = className.split("/");
		Class c;
		for(int i=0;i

附圖一張:

\


<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+PHN0cm9uZz7XoqO6PC9zdHJvbmc+PC9wPgo8cD4xIC4gudjT2tPOseqjqEN1cnNvcqOpPC9wPgo8cD4gICAg1Nqy6dGvt7W72LXEysfSu7j2Q3Vyc29ywODQzbXEttTP86Osy/zKx9K7uPbWuNXro6zH0tPA1La2vLK7u+HOqr/Vo6zL+dLUo6y1sbLp0a/Es9PvvuSjrLKixdC2z7e1u9gmIzIwNTQwO8rHt/HOqr/VyrGjrMfQzvDTw2N1cnNvcj09bnVsbLHtyr6ho7b409C49re9t6gsY3Vyc29yLmdldENvdW50KCk9PTC+zcTcxdC2z8bkveG5+yYjMjA1NDA7yse38c6qv9XBy6GjPGJyPgo8L3A+CjxwPmNsb3NlKCkgPGJyPgq52LHV086x6qOsys23xdfK1LQgPGJyPgpjb3B5U3RyaW5nVG9CdWZmZXIoaW50IGNvbHVtbkluZGV4LCBDaGFyQXJyYXlCdWZmZXIgYnVmZmVyKSB5Qjxicj4K1Nq7urPlx/jW0Lzsy/fH68fztcTB0LXEzsSxvqOsvau9q8bktOa0oiA8YnI+CmdldENvbHVtbkNvdW50KCkgPGJyPgq3tbvYy/nT0MHQtcTX3Mr9IDxicj4KZ2V0Q29sdW1uSW5kZXgoU3RyaW5nIGNvbHVtbk5hbWUpIDxicj4Kt7W72Na4tq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ru49rDgvLa1xNPvvuS1xMqxuvLQ6NKq1rTQ0GRiLmV4ZWNTUUwo"PRAGMA foreign_keys=ON")

可見:http://blog.csdn.net/tangnengwu/article/details/25980263

可執行代碼:

http://download.csdn.net/detail/tangnengwu/7369503




  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved