当前位置:Gxlcms > 数据库问题 > 轻量级数据库sqlite的使用

轻量级数据库sqlite的使用

时间:2021-07-01 10:21:17 帮助过:5人阅读

本文不涉及一些概念性的东西,请大家多多原谅


技术分享


这个就是Android sqlite的简单框架。

使用sqlite 大概分为3步

第一步:创建自己的sqliteopenhelper类

第二步:创建数据库中的dao层 ,其中分装了对数据库的操作

第三步:在activity 中使用dao层的操作了(多线程的形式,防止卡界面)


第一步:创建 sqliteopenhelper

/**
 * @author skyfin
 *@time 2015/6/4
 */
public class MyDatabase extends SQLiteOpenHelper {

	/**
	 * 数据库的名字
	 */
	public final static String DB_NAME = "ClassaateInfo";

	/**
	 * 数据库的版本号
	 */
	public final static int VERSION = 1;

	/**
	 * @param 默认构造的函数
	 */
	public MyDatabase(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
		// TODO 自动生成的构造函数存根
	}

	public MyDatabase(Context context, String name, CursorFactory factory,
			int version, DatabaseErrorHandler errorHandler) {
		super(context, name, factory, version, errorHandler);
		// TODO
	}

	/**
	 * @param 为了每次不用传入数据库名和版本信息
	 */
	public MyDatabase(Context context) {
		this(context, DB_NAME, null, VERSION);
	}

	/**
	 * @param 为了更新数据库名和版本信息
	 */
	public MyDatabase(Context context, int version) {
		this(context, DB_NAME, null, version);
	}

	/*
	 * (非 Javadoc)
	 * 
	 * @see
	 * android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite
	 * .SQLiteDatabase)
	 * 创建了数据库 主键 id name 和phone
	 */
	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO 创建数据库对数据库的操作
		String sql = "create table IF NOT EXISTS student"+"("
				+ "id int primary key autoincrement," + "name varchar(20),"
				+ "phone int)";
		db.execSQL(sql);
	}

	/* (非 Javadoc)
	 * @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
	 * 
	 * 更改数据库版本的操作
	 */
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO 更改数据库版本的操作
		//String sql = "updete student ";
		//db.execSQL(sql);
	}

	@Override
	public void onOpen(SQLiteDatabase db) {
		// TODO 打开数据库
		super.onOpen(db);
	}

}


第二步:创建StudentDao 封装了 相关的操作

public class StudentDao {

	MyDatabase myDatabase = null;

	public StudentDao(Context context) {
		myDatabase = new MyDatabase(context);
	}

	public StudentDao(Context context, int version) {
		myDatabase = new MyDatabase(context, version);
	}

	/**
	 * 
	 * @param 实现数据的插入
	 */
	public void insertData(Student stu) {

		/*
		 * 方法一 使用了(?)的占位符 ,重载后的execSQL(String sql, Object[] bindArgs)方法
		 */

		// try {
		// Log.i("skyfin", "insert datebase" + stu.id);
		// String sql = "insert into student(id,name,phone)values(?,?,?)";
		// SQLiteDatabase db = myDatabase.getWritableDatabase();
		// db.execSQL(sql, new Object[] { stu.id, stu.name, stu.phone });
		// db.close();
		// } catch (Exception e) {
		// e.printStackTrace();
		// // TODO: handle exception
		// }

		/*
		 * 方法二 使用了 ContentValues字段存放的形式
		 */
		SQLiteDatabase db = myDatabase.getWritableDatabase();
		ContentValues values = new ContentValues();

		values.put("id", stu.id);
		values.put("name", stu.name);
		values.put("phone", stu.phone);

		long rowid = db.insert("student", null, values);// 返回新添记录的行号,与主键id无关
		db.close();
	}

	// 测试
	public void insert() {

		Log.i("skyfin", "test");
	}

	public void seleteAll() {
		
		/*
		 * 
		 * 方法一  query 形式
		 */
		
		 try {
		 Log.i("skyfin", "select  datebase");
		 String sql = "select  * from student";
		
		 SQLiteDatabase db = myDatabase.getWritableDatabase();
		 // 产生一个新的游标,游标课向前和向后
		 Cursor cursor = db.rawQuery(sql,null);
		 while(cursor.moveToNext()){
		 int id = cursor.getInt(cursor.getColumnIndex("id"));
		 String name = cursor.getString(cursor.getColumnIndex("name"));
		 int phone = cursor.getInt(cursor.getColumnIndex("phone"));
		 //日志打印输出
		 Log.i("skyfin","query-->"+"id: "+id+"name: "+name+"phone: "+phone);
		 }
		 db.close();
		 } catch (Exception e) {
		 // TODO 自动生成的 catch 块
		 e.printStackTrace();
		 }
		
		/*
		 * 
		 * 方法二  query 形式
		 */
//		try {
//			SQLiteDatabase db = myDatabase.getWritableDatabase();
//			Cursor cursor = db.query("student",
//					new String[] { "id","name","phone" }, null,
//					null, null, null, null, null);
//
//			while (cursor.moveToNext()) {
//				Log.i("skyfin", "cursor");
//				int id = cursor.getInt(cursor.getColumnIndex("id"));
//				String name = cursor.getString(cursor.getColumnIndex("name"));
//				int phone = cursor.getInt(cursor.getColumnIndex("phone"));
//				// 日志打印输出
//				Log.i("skyfin", "query-->" + "id: " + id + "name: " + name
//						+ "phone: " + phone);
//
//			}
//			cursor.close();
//			db.close();
//		} catch (Exception e) {
//			// TODO 自动生成的 catch 块
//			e.printStackTrace();
//		}

	}

	public void update() {
		try {
			SQLiteDatabase db = myDatabase.getWritableDatabase();

			//ContentValues 是一种 key -value 的形式 ,类似于map
			ContentValues values = new ContentValues();

			values.put("id", 1020);//key为字段名,value为值
			values.put("name","doubi");
			values.put("phone", 1234);
			//update 函数后面表示 条件
			db.update("student", values, "id=?", new String[]{"123"}); 
			db.close();
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}

	}
	public void delete(){
		SQLiteDatabase db = myDatabase.getWritableDatabase();
		//和update类似
		db.delete("student", "id<?", new String[]{"2000"});
		db.close();
	}

}

最后在 Activity中使用

public class MainActivity extends Activity implements OnClickListener {

	public StudentDao studentDao = null;
	public EditText edit_Id= null;
	public EditText edit_Name= null;
	public EditText edit_Phone= null;
	public Button ok_btn = null;
	public Button show_btn = null;
	public Button update_btn = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        studentDao = new StudentDao(getApplicationContext());
        edit_Id = (EditText)findViewById(R.id.id);
        edit_Name = (EditText)findViewById(R.id.name);
        edit_Phone = (EditText)findViewById(R.id.phonenum);
        ok_btn = (Button)findViewById(R.id.ok);
        show_btn = (Button)findViewById(R.id.show);
        update_btn = (Button)findViewById(R.id.update);
        ok_btn.setOnClickListener(this);
        show_btn.setOnClickListener(this);
        update_btn.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

	@Override
	public void onClick(View v) {
		// TODO 自动生成的方法存根
	
		
		switch (v.getId()) {
		case R.id.ok:	
			Toast.makeText(getApplicationContext(), "点击了确认按钮", Toast.LENGTH_SHORT).show();  
			Log.i("skyfin", "insert into datebase");
			
			final Student student = new Student();
			student.setId(Integer.parseInt(edit_Id.getText().toString()));
			student.setName(edit_Name.getText().toString());
			student.setPhone(Integer.parseInt(edit_Phone.getText().toString()));
			
			Log.i("skyfin", student.toString());
		    new Thread(new Runnable() {
				
				@Override
				public void run() {
					Log.i("skyfin", "insert thread is running");	
					studentDao.insertData(student);
				
				}
			}).start();
			
			break;
		case R.id.show:
			 new Thread(new Runnable() {
					
					@Override
					public void run() {
						Log.i("skyfin", "select  thread is running");	
						studentDao.seleteAll();
					
					}
				}).start();
			break;
			
		case R.id.update:
			 new Thread(new Runnable() {
					
					@Override
					public void run() {
						Log.i("skyfin", "update  thread is running");	
						studentDao.update();
						//studentDao.delete();
					
					}
				}).start();
			break;
		default:
			break;
		}
	}
}


dome下载地址

轻量级数据库sqlite的使用

标签:

人气教程排行