使用SQLiteHelper创建数据库并插入数据

参考《疯狂android讲义》8.4节P424

1、获取SQLiteDatabase实例有2种方法,一是直接new SQLiteDatabase(),另一种使用SQLiteHelper。一般建议使用后者。


使用SQLiteHelper插入数据的一般步骤:

package com.ljh.sqllitehelperdemo.helper;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {
	
	final private String CREATE_TABLE_SQL = "create table dict(_id integer primary key autoincrement, word, detail)";

	public DatabaseHelper(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
	}

	//1、创建SQLiteOpenHelper的子类,并重写onCreate及onUpgrade方法。
	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(CREATE_TABLE_SQL);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

}

package com.ljh.sqllitehelperdemo;

import com.ljh.sqllitehelperdemo.helper.DatabaseHelper;

import android.os.Bundle;
import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
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;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	private EditText etWord = null;
	private EditText etDetail = null;
	private EditText etSearchWord= null;
	private TextView tvDetail = null;
	private Button btInsert = null;
	private Button btSearch = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		etWord = (EditText) findViewById(R.id.et_word);
		etDetail = (EditText) findViewById(R.id.et_detail);
		etSearchWord = (EditText) findViewById(R.id.et_search_content);
		tvDetail = (TextView) findViewById(R.id.tv_detail);
		btInsert = (Button) findViewById(R.id.bt_insert);
		btSearch = (Button) findViewById(R.id.bt_search);
		
		//2、获取SQLiteOpenHelper的实例,并由此获取SQLiteDatabase实例。
		DatabaseHelper helper = new DatabaseHelper(this, this.getFilesDir()+"dict.db3",null,1);
		final SQLiteDatabase db = helper.getWritableDatabase();
		
		btInsert.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				String word = etWord.getText().toString();
				String detail = etDetail.getText().toString();
				insertData(db, word,detail);
				Toast.makeText(MainActivity.this, "插入数据成功", Toast.LENGTH_LONG).show();
			}
		});
		
	}
	
	private void insertData(SQLiteDatabase db, String word, String detail){
		//4、执行SQL语句。
		db.execSQL("insert into dict(word, detail) values(?,?)", new String[]{word,detail});
		
	}
}



你可能感兴趣的:(使用SQLiteHelper创建数据库并插入数据)